Python Lists
In Python, lists are a versatile data type used to store multiple items in a single variable. They are ordered, mutable, and allow duplicate elements. Lists are commonly used for managing collections of items, such as numbers, strings, or even other lists.
1. Creating a List
You can create a list by placing elements inside square brackets [], separated by commas.
Example:
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A mixed list
mixed_list = [1, "apple", 3.14, True]
2. Accessing List Elements
You can access elements in a list using their index. Python uses zero-based indexing, meaning the first element has index 0.
Example:
# Accessing elements by index
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple (first element)
print(fruits[1]) # Output: banana (second element)
Negative indexing can also be used to access elements from the end of the list.
Example:
print(fruits[-1]) # Output: cherry (last element)
print(fruits[-2]) # Output: banana (second-to-last element)
3. Slicing Lists
You can slice a list to extract a portion of it. The syntax for slicing is list[start:stop:step].
startis the index where the slice begins (inclusive).stopis the index where the slice ends (exclusive).stepdetermines the increment between elements in the slice.
Example:
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slicing a list
print(numbers[2:5]) # Output: [2, 3, 4] (elements from index 2 to 4)
print(numbers[:4]) # Output: [0, 1, 2, 3] (elements from the start 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 second element)
4. Modifying Lists
Lists are mutable, meaning you can change, add, or remove elements after the list is created.
4.1. Changing an Element
You can change an element in the list by accessing it using its index and assigning a new value.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "orange"
print(fruits) # Output: ['apple', 'orange', 'cherry']
4.2. Adding Elements
You can use the append(), insert(), or extend() methods to add elements to a list.
append()adds an element to the end of the list.insert()adds an element at a specified index.extend()adds all elements of an iterable (like another list) to the list.
fruits = ["apple", "banana"]
# Using append()
fruits.append("cherry")
print(fruits) # Output: ['apple', 'banana', 'cherry']
# Using insert() to add an element at a specific position
fruits.insert(1, "orange")
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']
# Using extend() to add multiple elements
fruits.extend(["grape", "melon"])
print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry', 'grape', 'melon']
4.3. Removing Elements
You can remove elements using remove(), pop(), or del.
remove()removes the first occurrence of a specified value.pop()removes an element at a specific index (or the last element by default).delcan be used to delete an element or an entire list.
fruits = ["apple", "banana", "cherry", "orange"]
# Using remove() to remove a value
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
# Using pop() to remove an element by index (or the last element)
last_fruit = fruits.pop()
print(last_fruit) # Output: orange
print(fruits) # Output: ['apple', 'cherry']
# Using del to remove an element by index
del fruits[0]
print(fruits) # Output: ['cherry']
5. List Length
To find the number of elements in a list, you can use the len() function.
fruits = ["apple", "banana", "cherry"]
print(len(fruits)) # Output: 3
6. List Concatenation and Repetition
You can concatenate lists using the + operator and repeat a list using the * operator.
Example:
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Concatenating lists
combined = list1 + list2
print(combined) # Output: [1, 2, 3, 4, 5, 6]
# Repeating a list
repeated = list1 * 3
print(repeated) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
7. List Comprehensions
List comprehensions provide a concise way to create lists using a single line of code.
Syntax:
[expression for item in iterable if condition]
Example:
# Create a list of squares of even numbers from 0 to 9
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares) # Output: [0, 4, 16, 36, 64]
8. Nested Lists
You can create lists that contain other lists. These are called nested lists.
Example:
nested_list = [[1, 2], [3, 4], [5, 6]]
# Accessing elements in a nested list
print(nested_list[0]) # Output: [1, 2]
print(nested_list[0][1]) # Output: 2
9. List Methods
Python lists come with a variety of built-in methods. Here are a few commonly used methods:
| Method | Description | Example |
|---|---|---|
append() | Adds an element to the end of the list | list.append(4) |
extend() | Adds all elements of an iterable to the list | list.extend([5, 6]) |
insert() | Adds an element at a specified index | list.insert(2, 4) |
remove() | Removes the first occurrence of a value | list.remove(3) |
pop() | Removes an element at a specified index or the last element | list.pop(1) |
clear() | Removes all elements from the list | list.clear() |
index() | Returns the index of the first occurrence of a value | list.index(2) |
count() | Returns the number of occurrences of a value | list.count(2) |
sort() | Sorts the list in ascending order | list.sort() |
reverse() | Reverses the elements in the list | list.reverse() |
Example:
fruits = ["apple", "banana", "cherry"]
# Using some list methods
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.sort()
print(fruits) # Output: ['apple', 'cherry', 'orange']
fruits.reverse()
print(fruits) # Output: ['orange', 'cherry', 'apple']
Summary:
- Lists are ordered, mutable, and can contain elements of different types.
- Lists support indexing, slicing, and various methods for adding, removing, and modifying elements.
- List comprehensions allow you to create lists concisely.
- Lists can be nested, meaning one list can contain other lists.