Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- TODO: I need some way to verify that I remember the important operations. Right now I can remember a handful of the things off the top of my head but I inevitably forget something. I think the ideal would be to have some kind of random quiz that asks you to accomplish certain things, and it makes sure it tests for every thing you can do with lists.
- """
- # Create a list
- my_list = [1, 2, 3, 4, 5]
- # Access elements
- first_element = my_list[0] # Access the first element
- last_element = my_list[-1] # Access the last element
- # Modify elements
- my_list[2] = 10 # Modify the third element
- # Add elements
- my_list.append(6) # Add an element to the end
- my_list.insert(2, 7) # Insert an element at a specific position
- # Remove elements
- my_list.remove(4) # Remove the first occurrence of an element
- removed_element = my_list.pop() # Remove and return the last element
- second_element = my_list.pop(1) # Remove and return the second element
- # List length
- length = len(my_list) # Get the number of elements in the list
- # Slicing
- sub_list = my_list[1:4] # Get a sublist (from index 1 to 3)
- every_other_element = my_list[::2] # Get every other element
- # List concatenation
- another_list = [8, 9]
- concatenated_list = my_list + another_list # Concatenate two lists
- # List repetition
- repeated_list = my_list * 2 # Repeat the list
- # Check for element existence
- is_in_list = 7 in my_list # Check if an element exists in the list
- # List comprehension
- squares = [x**2 for x in my_list] # Create a new list with the squares of the elements
- # Iterating through a list
- for element in my_list:
- print(element) # Print each element
- # List methods
- my_list.sort() # Sort the list in ascending order
- my_list.reverse() # Reverse the list
- my_list.clear() # Remove all elements from the list
- # List copying
- copied_list = my_list.copy() # Create a shallow copy of the list
- # Nested lists
- nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
- first_sub_list = nested_list[0] # Access the first sublist
- element_in_nested_list = nested_list[1][2] # Access an element in a sublist
- # List conversion
- string_list = "1,2,3,4,5"
- converted_list = string_list.split(",") # Convert a string to a list
- back_to_string = ",".join(converted_list) # Convert a list to a string
Advertisement
Add Comment
Please, Sign In to add comment