Python Lists: Working with Ordered Collections of Data


Python lists are one of the most basic and versatile data types in Python. They are used to store an ordered collection of items, which can be of different types.

Here are some examples of how to create and manipulate lists in Python:

# Creating a list >>> a = [1, 2, 3, 4, 5] >>> b = ['a', 'b', 'c'] >>> c = [1, 'a', 2, 'b', 3, 'c'] # Accessing elements in a list >>> a[0] # Returns the first element of the list 1 >>> a[-1] # Returns the last element of the list 5 # Modifying elements in a list >>> a[0] = 9 # Change the first element of the list >>> a [9, 2, 3, 4, 5] # Appending elements to a list >>> a.append(6) # Append 6 to the end of the list >>> a [9, 2, 3, 4, 5, 6] # Inserting elements into a list >>> a.insert(0, 0) # Insert 0 at the beginning of the list >>> a [0, 9, 2, 3, 4, 5, 6] # Removing elements from a list >>> a.pop() # Remove and return the last element of the list 6 >>> a.pop(0) # Remove and return the first element of the list 0 # Finding the index of an element in a list >>> a.index(3) # Returns the index of the first occurrence of 3 in the list 2 # Checking if an element is in a list >>> 3 in a # Returns True if 3 is in the list, False otherwise True >>> 10 in a # Returns False because 10 is not in the list False # Sorting a list >>> a.sort() # Sorts the list in ascending order >>> a [2, 3, 4, 5, 9] # Reversing a list >>> a.reverse() # Reverses the order of the elements in the list >>> a [9, 5, 4, 3, 2] # Copying a list >>> b = a.copy() # Creates a copy of the list >>> b [9, 5, 4, 3, 2] # Clearing a list >>> a.clear() # Removes all elements from the list >>> a []

I hope this helps! Let me know if you have any questions.

Comments