A list in Python is an ordered collection of elements enclosed in square brackets [ ]. Lists are mutable, meaning you can modify their contents after creation.
Accessing List Elements
To access elements in a list, use their index position starting from 0. Python lists are zero-indexed, so the first element is at index 0, the second at index 1, and so on.
Using List Values
Once accessed, list elements can be used just like regular variables in your Python code.
Modifying, Adding, and Removing Elements
Python lists are dynamic data structures that allow you to modify, add, and remove elements easily.
Modifying List Elements
To modify an element, access it by its index and assign a new value. Other elements in the list remain unchanged.
fruits = ['apple', 'banana', 'cherry', 'date']
fruits[2] = 'elderberry'
print(fruits)
# Output: ['apple', 'banana', 'elderberry', 'date']
Adding Elements to Lists
Append to the end: Use the appand() method to add an element to the end of the list.
fruits.append('fig')
# fruits becomes: ['apple', 'banana', 'elderberry', 'date', 'fig']
Insert at specific position: Use the insert() method to add an element at any position. The first parameter is the index where you want to insert, and the second is the value.
fruits.insert(1, 'grape')
# Insert at index 1, pushing existing elements to the right
Removing Elements from Lists
Using del statement: Remove a element by its index when you don't need the removed value.
del fruits[0] # Removes the first element
Using pop() method: Remove and return the last element (default) or an element at a specific index.
numbers = [10, 20, 30, 40]
last_item = numbers.pop() # Removes 40
print(f"Removed: {last_item}")
print(f"Remaining: {numbers}")
# Output:
# Removed: 40
# Remaining: [10, 20, 30]
Popping from specific index:
second_item = numbers.pop(1) # Removes element at index 1 (20)
Removing by value: Use the remove() method when you know the value but not the index.
fruits.remove('banana') # Removes the first occurrence of 'banana'
Organizing Lists
Permanent Sorting with sort()
The sort() method arranges list elements in alphabetical (or numerical) order permanently. The change cannot be undone.
vegetables = ['carrot', 'broccoli', 'asparagus']
vegetables.sort()
# vegetables becomes: ['asparagus', 'broccoli', 'carrot']
# Reverse sorting
vegetables.sort(reverse=True)
# vegetables becomes: ['carrot', 'broccoli', 'asparagus']
Temporary Sorting with sorted()
The sorted() function returns a new sorted list without modifying the original list.
colors = ['red', 'blue', 'green', 'yellow']
sorted_colors = sorted(colors)
print(f"Sorted: {sorted_colors}")
print(f"Original: {colors}")
# Output:
# Sorted: ['blue', 'green', 'red', 'yellow']
# Original: ['red', 'blue', 'green', 'yellow']
Reversing List Order
The reverse() method permanently reverses the list order. You can restore the original order by calling reverse() again.
animals = ['lion', 'tiger', 'bear']
animals.reverse()
# animals becomes: ['bear', 'tiger', 'lion']
Getting List Length
Use the len() function to determine the number of elements in a list.
planets = ['mercury', 'venus', 'earth', 'mars']
print(len(planets)) # Output: 4
Avoiding Index Errors
Remember that Python list indices start at 0 and go up to len(list) - 1. If you encounter an IndexError, use len() to verify your list's length and ensure you're accessing valid indices.
For example, if a list has 5 elements, valid indices are 0 through 4. Attempting to access index 5 will raise an error.
Pro tip: Use -1 to access the last element, -2 for the second-to-last, and so on. This helps avoid index errors when working with lists of unknown length.