Lists are one of the most versatile and widely used data structures in Python. A list is an ordered, mutable (changeable) collection of items. Items in a list do not have to be of the same data type. Lists are defined by enclosing elements in square brackets [], separated by commas.
Creating Lists
python# An empty list empty_list = [] # A list of integers numbers = [1, 2, 3, 4, 5] # A list of strings fruits = ["apple", "banana", "cherry"] # A mixed-type list mixed_list = [1, "hello", True, 3.14] # Nested lists (list containing other lists) matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print(empty_list) print(numbers) print(fruits) print(mixed_list) print(matrix) print(type(numbers)) # Output: <class 'list'>
Accessing List Elements (Indexing)
Like strings, list elements are accessed using their index, starting from 0 for the first element.
- Positive indexing:
list[0]for the first element. - Negative indexing:
list[-1]for the last element.
pythonmy_list = ['P', 'y', 't', 'h', 'o', 'n'] print(my_list[0]) # Output: P print(my_list[2]) # Output: t print(my_list[-1]) # Output: n (last element) print(my_list[-3]) # Output: h (third from last) # Accessing elements in nested lists print(matrix[0][1]) # Output: 2 (row 0, column 1)
Slicing Lists
Slicing allows you to get a sub-list from a larger list.
The syntax is `list[start:
end:step]`, similar to string slicing.
pythonnumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:6]) # Output: [2, 3, 4, 5] (elements from index 2 up to, but not including, 6) print(numbers[:5]) # Output: [0, 1, 2, 3, 4] (from beginning to index 5) print(numbers[7:]) # Output: [7, 8, 9] (from index 7 to the end) print(numbers[::2]) # Output: [0, 2, 4, 6, 8] (every second element) print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reversed list)
Modifying Lists (Mutating)
Lists are mutable, meaning you can change, add, or remove elements after creation.
**1.
Changing an element:
**
pythonfruits = ["apple", "banana", "cherry"] fruits[1] = "orange" # Change 'banana' to 'orange' print(fruits) # Output: ['apple', 'orange', 'cherry']
**2.
Adding elements:
**
list.append(item): Adds an item to the end of the list.list.insert(index, item): Inserts an item at a specified index.list.extend(another_list): Appends elements from another iterable to the end of the list.
pythonfruits.append("grape") print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape'] fruits.insert(1, "kiwi") print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry', 'grape'] more_fruits = ["mango", "pineapple"] fruits.extend(more_fruits) print(fruits) # Output: ['apple', 'kiwi', 'orange', 'cherry', 'grape', 'mango', 'pineapple']
**3.
Removing elements:
**
list.remove(item): Removes the first occurrence of the specified item.list.pop(index): Removes and returns the item at the given index (defaults to the last item).del list[index]ordel list[start:end]: Deletes item(s) by index or slice.list.clear(): Removes all items from the list.
pythonfruits.remove("orange") print(fruits) # Output: ['apple', 'kiwi', 'cherry', 'grape', 'mango', 'pineapple'] popped_item = fruits.pop(0) # Pop the first item print(f"Popped: {popped_item}, Remaining: {fruits}") # Output: Popped: apple, Remaining: ['kiwi', 'cherry', 'grape', 'mango', 'pineapple'] del fruits[1:3] # Delete 'cherry' and 'grape' print(fruits) # Output: ['kiwi', 'mango', 'pineapple'] fruits.clear() print(fruits) # Output: []
Other Useful List Methods
len(list): Returns the number of items in the list.list.count(item): Returns the number of timesitemappears in the list.list.sort(): Sorts the list in ascending order (in-place modification).sorted(list): Returns a new sorted list (does not modify the original).list.reverse(): Reverses the order of elements (in-place modification).
Lists are incredibly powerful for storing collections where order and mutability are important. They are a cornerstone of almost every Python program.
Key Takeaways:
- Lists are ordered, changeable collections, defined with
[]. - Elements can be of any data type and accessed by index (
[0]for first,[-1]for last). - Slicing (
[start:end]) extracts sub-lists. - Lists are mutable: elements can be changed, added (
append(),insert(),extend()), or removed (remove(),pop(),del,clear()). - Useful methods include
len(),count(),sort(),sorted(),reverse().