Python Lists: A Comprehensive Guide
Lists are one of the most versatile and fundamental data structures in Python. They are used to store collections of items, and are mutable, meaning you can change their contents after creation.
1. What is a List?
- A list is an ordered sequence of items.
- Items in a list can be of different data types (integers, floats, strings, other lists, etc.).
- Lists are defined using square brackets
[]. - Items are separated by commas.
Example:
my_list = [1, 2.5, "hello", [3, 4]]
print(my_list) # Output: [1, 2.5, 'hello', [3, 4]]
2. Creating Lists
There are several ways to create lists:
Directly using square brackets:
empty_list = [] numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed_list = [1, "apple", 3.14, True]Using the
list()constructor:From an iterable (e.g., string, tuple, set):
string = "Python" char_list = list(string) # Output: ['P', 'y', 't', 'h', 'o', 'n'] tuple_data = (1, 2, 3) list_from_tuple = list(tuple_data) # Output: [1, 2, 3]To create an empty list:
empty_list = list()
List Comprehensions (covered later) - a concise way to create lists.
3. Accessing List Elements (Indexing)
List elements are accessed using their index. Python uses zero-based indexing, meaning the first element has an index of 0.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana
print(fruits[2]) # Output: cherry
# Negative indexing: Access elements from the end
print(fruits[-1]) # Output: cherry (last element)
print(fruits[-2]) # Output: banana (second to last element)
Important: Trying to access an index that is out of range will raise an IndexError.
# Example of IndexError
# print(fruits[3]) # Raises IndexError: list index out of range
4. Slicing Lists
Slicing allows you to extract a portion of a list.
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5]) # Output: [2, 3, 4] (elements from index 2 up to, but not including, index 5)
print(numbers[:3]) # Output: [0, 1, 2] (elements from the beginning up to index 3)
print(numbers[5:]) # Output: [5, 6, 7, 8, 9] (elements from index 5 to the end)
print(numbers[::2]) # Output: [0, 2, 4, 6, 8] (every other element)
print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] (reverse the list)
5. Modifying Lists (Mutability)
Lists are mutable, so you can change their contents after creation.
Changing an element:
fruits = ["apple", "banana", "cherry"] fruits[1] = "orange" print(fruits) # Output: ['apple', 'orange', 'cherry']Adding elements:
append(item): Adds an item to the end of the list.fruits = ["apple", "banana"] fruits.append("cherry") print(fruits) # Output: ['apple', 'banana', 'cherry']insert(index, item): Inserts an item at a specific index.fruits = ["apple", "banana"] fruits.insert(1, "orange") print(fruits) # Output: ['apple', 'orange', 'banana']extend(iterable): Adds elements from an iterable (e.g., another list) to the end of the list.fruits = ["apple", "banana"] more_fruits = ["cherry", "date"] fruits.extend(more_fruits) print(fruits) # Output: ['apple', 'banana', 'cherry', 'date']
Removing elements:
remove(item): Removes the first occurrence of a specific item.fruits = ["apple", "banana", "cherry", "banana"] fruits.remove("banana") print(fruits) # Output: ['apple', 'cherry', 'banana']pop(index): Removes and returns the item at a specific index (defaults to the last item if no index is provided).fruits = ["apple", "banana", "cherry"] removed_fruit = fruits.pop(1) print(fruits) # Output: ['apple', 'cherry'] print(removed_fruit) # Output: bananadel list[index]: Deletes the item at the specified index.fruits = ["apple", "banana", "cherry"] del fruits[0] print(fruits) # Output: ['banana', 'cherry']clear(): Removes all items from the list.fruits = ["apple", "banana", "cherry"] fruits.clear() print(fruits) # Output: []
6. List Operations
len(list): Returns the number of items in the list.fruits = ["apple", "banana", "cherry"] print(len(fruits)) # Output: 3+(Concatenation): Creates a new list by combining two lists.list1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = list1 + list2 print(combined_list) # Output: [1, 2, 3, 4, 5, 6]*(Repetition): Creates a new list by repeating the original list a specified number of times.numbers = [1, 2] repeated_list = numbers * 3 print(repeated_list) # Output: [1, 2, 1, 2, 1, 2]in(Membership): Checks if an item is present in the list.fruits = ["apple", "banana", "cherry"] print("banana" in fruits) # Output: True print("orange" in fruits) # Output: False
7. List Methods
Here's a summary of common list methods:
| Method | Description |
|---|---|
append() |
Adds an element to the end of the list. |
clear() |
Removes all elements from the list. |
copy() |
Returns a shallow copy of the list. |
count() |
Returns the number of occurrences of an element. |
extend() |
Extends the list by appending elements from an iterable. |
index() |
Returns the index of the first occurrence of an element. |
insert() |
Inserts an element at a specific index. |
pop() |
Removes and returns an element by index. |
remove() |
Removes the first occurrence of an element. |
reverse() |
Reverses the order of elements in the list. |
sort() |
Sorts the elements in the list (in-place). |
8. List Comprehensions
List comprehensions provide a concise way to create lists based on existing iterables.
# Create a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]