Lists are one of the most versatile and commonly used data structures in Python. They allow you to store multiple items in a single variable and can hold items of different data types.
Key Features of Python Lists
- Ordered: Lists maintain the order of elements. Items can be accessed using an index.
- Mutable: Lists can be modified after creation (add, remove, or change items).
- Dynamic: Lists can grow or shrink in size.
- Heterogeneous: A list can store items of different data types.
Creating Lists
To create a list, use square brackets []
.
# Empty list
empty_list = []
# List of integers
numbers = [1, 2, 3, 4]
# List of strings
fruits = ["apple", "banana", "cherry"]
# Mixed data types
mixed_list = [1, "hello", 3.14, True]
# Nested list (list inside a list)
nested_list = [[1, 2], [3, 4], [5, 6]]
Accessing List Items
List items can be accessed using indexing (starting from 0) or negative indexing (starting from -1 for the last item).
fruits = ["apple", "banana", "cherry"]
# Access by index
print(fruits[0]) # Output: apple
# Access by negative index
print(fruits[-1]) # Output: cherry
Slicing Lists
Slicing allows you to extract a subset of the list.
numbers = [10, 20, 30, 40, 50]
# Slicing from index 1 to 3
print(numbers[1:4]) # Output: [20, 30, 40]
# Slicing from the start to index 2
print(numbers[:3]) # Output: [10, 20, 30]
# Slicing from index 2 to the end
print(numbers[2:]) # Output: [30, 40, 50]
# Slicing with step
print(numbers[::2]) # Output: [10, 30, 50]
Modifying Lists
Lists are mutable, so you can modify them using indexing or built-in methods.
Changing an Item
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits) # Output: ["apple", "blueberry", "cherry"]
Adding Items
append()
: Adds an item to the end of the list.insert()
: Inserts an item at a specific index.
fruits.append("orange")
print(fruits) # Output: ["apple", "blueberry", "cherry", "orange"]
fruits.insert(1, "grape")
print(fruits) # Output: ["apple", "grape", "blueberry", "cherry", "orange"]
Removing Items
remove()
: Removes the first occurrence of a specified value.pop()
: Removes an item by index (default is the last item).del
: Deletes an item or the entire list.
fruits.remove("grape")
print(fruits) # Output: ["apple", "blueberry", "cherry", "orange"]
fruits.pop(2)
print(fruits) # Output: ["apple", "blueberry", "orange"]
del fruits[1]
print(fruits) # Output: ["apple", "orange"]
Clearing a List
clear()
: Removes all items from the list.
fruits.clear()
print(fruits) # Output: []
List Operations
Concatenation
Combine two or more lists using the +
operator.
list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4]
Repetition
Repeat a list using the *
operator.
numbers = [1, 2, 3]
repeated = numbers * 2
print(repeated) # Output: [1, 2, 3, 1, 2, 3]
Membership Test
Check if an item exists in a list using in
or not in
.
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # Output: True
print("grape" not in fruits) # Output: True
Iterating Through a List
Use a for
loop to iterate through the list items.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
List Methods
Python provides many built-in methods to manipulate lists:
Method | Description | Example |
---|---|---|
append() | Adds an item to the end of the list | fruits.append("orange") |
extend() | Adds all items from another list to the current list | list1.extend(list2) |
insert() | Inserts an item at a specified position | fruits.insert(1, "grape") |
remove() | Removes the first occurrence of a specified value | fruits.remove("apple") |
pop() | Removes the item at a specified index (default: last) | fruits.pop(2) |
clear() | Removes all items from the list | fruits.clear() |
index() | Returns the index of the first occurrence of a value | fruits.index("banana") |
count() | Returns the number of occurrences of a value | fruits.count("apple") |
sort() | Sorts the list in ascending (default) or descending order | fruits.sort(reverse=True) |
reverse() | Reverses the order of the list | fruits.reverse() |
copy() | Returns a shallow copy of the list | new_list = fruits.copy() |
Example: List Manipulation
# Initial list
numbers = [10, 20, 30, 40, 50]
# Add items
numbers.append(60)
numbers.insert(2, 25)
# Remove items
numbers.remove(40)
numbers.pop(0)
# Sort the list
numbers.sort()
print(numbers) # Output: [20, 25, 30, 50, 60]
Nested Lists
Lists can contain other lists as elements, creating a nested structure.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# Accessing elements in a nested list
print(nested_list[1]) # Output: [4, 5, 6]
print(nested_list[1][2]) # Output: 6
Conclusion
Python lists are flexible and powerful, making them suitable for a wide range of applications. Understanding how to manipulate lists effectively is essential for mastering Python programming.