Python lists are ordered mutable collections of objects, which are one of the most versatile and frequently used data structures. They can contain elements of different data types: numbers, strings, other lists, functions, and any Python objects. Lists support a variety of operations for adding, deleting, changing items, and working with content.
Basics of working with lists
Creating a list
To create a list in Python, square brackets [] are used, inside which the elements are separated by commas.:
# Creating an empty list
empty_list = []
# Creating a list with items of different types
my_list = [1, 2, 3, 'apple', 'banana', True]
# Creating a list using the list() constructor
numbers = list(range(5)) # [0, 1, 2, 3, 4]
Access to list items
The list items are indexed starting from zero. Square brackets with an index are used to access the elements.:
my_list = [1, 2, 3, 'apple', 'banana', True]
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: 'apple'
print(my_list[-1]) # Output: True (last element)
print(my_list[-2]) # Output: 'banana' (penultimate element)
Changing list items
Since lists are mutable, you can easily modify their elements:
my_list = [1, 2, 3, 'apple', 'banana', True]
my_list[1] = 'orange'
print(my_list) # Output: [1, 'orange', 3, 'apple', 'banana', True]
Slicing of the list
Slices allow you to get a sublist from the original list.:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(my_list[1:4]) # Output: [1, 2, 3]
print(my_list[:5]) # Output: [0, 1, 2, 3, 4]
print(my_list[3:]) # Output: [3, 4, 5, 6, 7, 8, 9]
print(my_list[::2]) # Output: [0, 2, 4, 6, 8]
print(my_list[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Methods of working with lists
Adding elements
append() - adds an item to the end of the list:
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
extend() - expands the list by adding elements from the iterated object:
my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]
insert() - inserts the element at the specified position:
my_list = [1, 2, 3]
my_list.insert(1, 'a')
print(my_list) # Output: [1, 'a', 2, 3]
Deleting elements
remove() - removes the first occurrence of the specified element:
my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2]
pop() - deletes and returns the element at the specified index:
my_list = [1, 2, 3]
popped_item = my_list.pop(1)
print(popped_item) # Output: 2
print(my_list) # Output: [1, 3]
clear() - removes all items from the list:
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
del - deletes an element by index or the entire list:
my_list = [1, 2, 3, 4, 5]
del my_list[0]
print(my_list) # Output: [2, 3, 4, 5]
Searching and counting elements
index() - returns the index of the first occurrence of the element:
my_list = [1, 2, 3, 2]
print(my_list.index(2)) # Output: 1
count() - returns the number of occurrences of an element:
my_list = [1, 2, 3, 2]
print(my_list.count(2)) # Output: 2
in is the check operator for element occurrence:
my_list = [1, 2, 3]
print(2 in my_list) # Output: True
print(5 in my_list) # Output: False
Sorting and reordering
sort() - sorts the list items in place:
my_list = [3, 1, 4, 1, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 3, 4, 5]
# Sort in descending
order my_list.sort(reverse=True)
print(my_list) # Output: [5, 4, 3, 1, 1]
reverse() - reverses the order of the elements:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
Copying the list
copy() - creates a shallow copy of the list:
my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list) # Output: [1, 2, 3]
Iterating through the list
There are several ways to iterate through the list items:
my_list = ['apple', 'banana', 'cherry']
# Simple iteration
for item in my_list:
print(item)
# Iteration with indexes
for i, item in enumerate(my_list):
print(f"Index {i}: {item}")
# Index iteration
for i in range(len(my_list)):
print(f"my_list[{i}] = {my_list[i]}")
Useful functions for working with lists
my_list = [1, 5, 3, 9, 2]
print(len(my_list)) # List length: 5
print(max(my_list)) # Maximum element: 9
print(min(my_list)) # Minimum element: 1
print(sum(my_list)) # Sum of elements: 20
print(sorted(my_list)) # Sorted copy: [1, 2, 3, 5, 9]
List Comprehensions
List expressions allow you to create lists more compactly.:
# Creating a list of squares of numbers from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Filtering even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Converting strings to uppercase
words = ['hello', 'world', 'python']
upper_words = [word.upper() for word in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
Two-dimensional lists (matrices)
A two-dimensional list is a list whose elements are other lists, which allows you to create structures similar to tables or matrices.
Creating two-dimensional lists
# Creating a two-dimensional 3x3 list
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Creating a matrix using a list generator
matrix = [[0 for j in range(3)] for i in range(3)]
# Creating a matrix using multiplication (careful!)
# Wrong way:
wrong_matrix = [[0] * 3] * 3 # All lines refer to a single object
# The correct way is:
correct_matrix = [[0] * 3 for _ in range(3)]
Access to the elements of a two-dimensional list
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
print(matrix[0][0]) # Output: 1 (first row, first column)
print(matrix[1][2]) # Output: 6 (second row, third column)
print(matrix[2][1]) # Output: 8 (third row, second column)
Changing the elements of a two-dimensional list
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
matrix[0][0] = 10
print(matrix) # [[10, 2, 3], [4, 5, 6], [7, 8, 9]]
Iterating through a two-dimensional list
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Traversing all the elements
for row in matrix:
for element in row:
print(element, end=' ')
print() # Jump to a new line
# Crawling with indexes
for i in range(len(matrix)):
for j in range(len(matrix[i])):
print(f"matrix[{i}][{j}] = {matrix[i][j]}")
Operations with two-dimensional lists
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# Calculating the sum of all the elements
total_sum = sum(sum(row) for row in matrix)
print(total_sum) # 45
# Matrix transposition
transposed = [[matrix[j][i] for j in range(len(matrix))]
for i in range(len(matrix[0]))]
print(transposed) # [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
# Search for the maximum element
max_element = max(max(row) for row in matrix)
print(max_element) # 9
Multidimensional lists
Multidimensional lists can have a more complex structure with different levels of nesting.:
# Three-dimensional list
three_d_list = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
# Access to the elements
print(three_d_list[0][1][0]) # Output: 3
print(three_d_list[1][0][1]) # Output: 6
# Heterogeneous multidimensional list
multi_dim_list = [[1, 2, [3, 4]], [5, [6, 7], 8], [9, 10, 11]]
print(multi_dim_list[0][2][1]) # Output: 4
print(multi_dim_list[1][1][0]) # Output: 6
Practical usage examples
Working with data
# List of students and their grades
students = [
['Ivan', [5, 4, 5, 3]],
['Maria', [4, 5, 5, 4]],
['Peter', [3, 3, 4, 3]]
]
# Calculating the average grade for each student
for student in students:
name, grades = student
average = sum(grades) / len(grades)
print(f"{name}: {average:.2f}")
Playing field
# Creating a tic-tac-toe game board
board = [[' ' for _ in range(3)] for _ in range(3)]
# Character placement
board[0][0] = 'X'
board[1][1] = 'O'
board[2][2] = 'X'
# Field display
for row in board:
print('|'.join(row))
print('-' * 5)
Optimization of working with lists
Operational performance
# Effectively adding elements to the end
of my_list = []
for i in range(1000):
my_list.append(i) # O(1) operation
# Inefficient addition to the beginning
of my_list = []
for i in range(1000):
my_list.insert(0, i) # O(n) operation
# Efficient list aggregation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2 # Creates a new list
# or
list1.extend(list2) # Modifies an existing list
Saving memory
# Generators for large amounts of data
def number_generator(n):
for i in range(n):
yield i * i
# Using a generator instead of a list
squares = (x*x for x in range(1000000)) # Lazy calculation
Lists in Python are a powerful and flexible tool for storing and processing data. Understanding their features, methods, and effective use will help you create better and more productive programs. Due to the simplicity of the syntax and a rich set of built-in methods, lists remain one of the most popular data structures in Python development.
table of all the main list methods in python:
method element
| The | Syntax | Description | Example |
|---|---|---|---|
| append() | list.append(item) |
Adds an item to the end of the list | [1, 2].append(3) → [1, 2, 3] |
| insert() | list.insert(index, item) |
Inserts an element at the specified index | [1, 3].insert(1, 2) → [1, 2, 3] |
| extend() | list.extend(iterable) |
Adds all the elements from the iterated object | [1, 2].extend([3, 4]) → [1, 2, 3, 4] |
| remove() | list.remove(item) |
Deletes the first occurrence of the | [1, 2, 2, 3].remove(2) → [1, 2, 3] |
| pop() | list.pop([index]) |
Deletes and returns an element by index (the last one by default) | [1, 2, 3].pop() 3, list: [1, 2] |
| clear() | list.clear() |
Deletes all items from the list | [1, 2, 3].clear() → [] |
| index() | list.index(item, [start, end]) |
Returns the index of the first occurrence of the element | [1, 2, 3].index(2) → 1 |
| count() | list.count(item) |
Returns the number of occurrences of an element | [1, 2, 2, 3].count(2) → 2 |
| sort() | list.sort([key], [reverse]) |
Sorts the list in place | [3, 1, 2].sort() → [1, 2, 3] |
| reverse() | list.reverse() |
Expands the list in place | [1, 2, 3].reverse() → [3, 2, 1] |
| copy() | list.copy() |
Creates a shallow copy of the list | [1, 2, 3].copy() → [1, 2, 3] |
Additional operations (not methods, but important ones):
| Operation | Syntax | Description | Example |
|---|---|---|---|
| len() | len(list) |
Returns the length of the list | len([1, 2, 3]) → 3 |
| max() | max(list) |
Returns the maximum element | max([1, 3, 2]) → 3 |
| min() | min(list) |
Returns the minimum element | min([1, 3, 2]) → 1 |
| sum() | sum(list) |
Returns the sum of the elements | sum([1, 2, 3]) → 6 |
| sorted() | sorted(list) |
Returns a new sorted list | sorted([3, 1, 2]) → [1, 2, 3] |
| reversed() | reversed(list) |
Returns the iterator in reverse order | list(reversed([1, 2, 3])) → [3, 2, 1] |
Notes:
- Methods with modify modify the original list
- Methods with return return a new object without changing the original
- When using
remove()andindex()aValueErrormay occur if the element is not found pop()may causeIndexErrorwhen trying to delete from an empty list