Lists in Python: a detailed guide
A list is an ordered and mutable collection that can contain elements of various types. The word "mutable" means that you can add, delete, or modify list items after creating it. Lists in Python are similar to arrays in other programming languages, but they provide much more flexibility and built-in functions.
A useful tip: Use lists when the order of the items is important to you and when you may need to change the contents of the collection while the program is running.
Creating a list
The list is created using square brackets [] or using the constructor function list().
# Empty list
my_list = []
# A list with multiple my_list elements
= [1, 2, 3, 4, 5]
# A list with elements of different types
my_list = [1, "hello", 3.14, True]
# Creating a list from another iterable object, for example, the string
char_list = list("Python")
print(char_list) # Output: ['P', 'y', 't', 'h', 'o', 'n']
User input of the list
There are several ways to get a list from a user.
# Method 1: Input via the eval() function
# **ATTENTION:** It is EXTREMELY UNSAFE to use eval() with user input.,
# because it allows you to execute any arbitrary code.
# Use this method only for educational purposes and never in real projects.
my_list = eval(input("Enter the list in the format [1, 2, 3]: "))
print(my_list) # Output: [1, 2, 3]
# Method 2: The safe and preferred method
# Enter numbers separated by a space
s = input("Enter numbers separated by a space: ") # The user enters: 1 2 3 4 5
numbers_list = s.split() # We get a list of strings: ['1', '2', '3', '4', '5']
# To work with them as numbers, they need to be converted:
int_list = [int(num) for num in numbers_list]
print(int_list) # Output: [1, 2, 3, 4, 5]
Adding items to the list
Python provides several methods for adding items to a list:
append(): adds one item to the very end of the list. This is the fastest addition operation.
insert(): inserts an element into the specified position (by index), shifting the remaining elements.
extend(): Extends the list by adding to the end all the items from another collection (for example, another list).
numbers = [1, 2, 3]
# Adding an element to the end
of numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
# Inserting an element at position 1
numbers.insert(1, 10)
print(numbers) # Output: [1, 10, 2, 3, 4]
# Adding multiple items from another list
numbers.extend([5, 6, 7])
print(numbers) # Output: [1, 10, 2, 3, 4, 5, 6, 7]
A useful tip: You can also combine lists using the + operator, but this creates a completely new list, rather than modifying an existing one, unlike extend().
list1 = [1, 2]
list2 = [3, 4]
list3 = list1 + list2
print(list3) # Output: [1, 2, 3, 4]
print(list1) # Output: [1, 2] (remained unchanged)
Access to list items
The list items are available by index. Indexing starts with 0 for the first element. Negative indexing is also supported, where -1 is the last element.
my_list = [10, 20, 30, 40, 50]
# Access to the first element
of print(my_list[0]) # Output: 10
# Access to the last element
of print(my_list[-1]) # Output: 50
# Access to the element by index 2
print(my_list[2]) # Output: 30
Important: An attempt to access a non-existent index will cause an error IndexError. Always make sure that the index is within the length of the list.
Changing list items
You can easily change the list items by accessing them by index. This is one of the key differences between lists and strings, since strings in Python are immutable.
my_list = [10, 20, 30, 40, 50]
my_list[1] = 25 # Replace the element with index 1
print(my_list) # Output: [10, 25, 30, 40, 50]
Cross-sections of the list
Slices allow you to get parts of a list by creating a new list. Syntax: list[start:stop:step].
start: initial index (enabled). If omitted, the slice will start from the beginning of the list.
stop: end index (not included). If omitted, the slice will go to the end of the list.
step: step. If omitted, it is equal to 1.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice 2 to 5 index (elements with indexes 2, 3, 4, 5)
sublist = numbers[2:6]
print(sublist) # Output: [3, 4, 5, 6]
# Slice from the beginning to the 5th index
sublist = numbers[:6]
print(sublist) # Output: [1, 2, 3, 4, 5, 6]
# Slice from index 5 to the end
sublist = numbers[5:]
print(sublist) # Output: [6, 7, 8, 9]
# Every second element
sublist = numbers[::2]
print(sublist) # Output: [1, 3, 5, 7, 9]
# Creating a copy of the list in reverse order
sublist = numbers[::-1]
print(sublist) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1]
A useful tip: A slice always creates a new list (a shallow copy). This is a convenient way to copy the list: new_list = old_list[:].
Iterating through the list items
The lists can be iterated through using the for loop.
numbers = [1, 2, 3, 4, 5]
# Method 1: Direct search (preferably if you don't need an index)
# This method is more readable and "Pythonic"
for number in numbers:
print(number, end=" ")
# Output: 1 2 3 4 5
print() # for line wrapping
# Method 2: Index search (when the index itself is needed)
for i in range(len(numbers)):
print(f"Index {i}, value {numbers[i]}")
# Method 3: The ideal option when you need both an index and a value
# Use the built-in enumerate() function
for i, number in enumerate(numbers):
print(f"Index {i}, value {number}")
Processing of several neighboring elements
It is very important to keep in mind the range of the range function if you want to take several elements in one iteration of the loop so as not to go beyond the list.
numbers = [12, 6, 2, 4, 9, 6, 10]
# Comparing the current element with the next one
for i in range(len(numbers) - 1): # Go to the penultimate element
if numbers[i] > numbers[i+1]:
print(numbers[i], end=" ")
# Output: 12 6 9
General rule: If you access numbers[i+k] in the loop, then the range of the loop should be range(len(numbers) - k). For example, to process triples of elements (i, i+1, i+2), the loop will be for i in range(len(numbers) - 2).
Beautiful list content output
numbers = [1, 2, 3, 4, 5]
# Method 1: Through a loop and the end parameter
for i in range(len(numbers)):
print(numbers[i], end=" ")
# Output: 1 2 3 4 5
print() # for line wrapping
# Method 2: More elegant and modern
# Using the "*" operator (unpacking the list)
print(*numbers) # by default, the separator is a space
# Output: 1 2 3 4 5
# You can specify any other separator
print(*numbers, sep=", ")
# Output: 1, 2, 3, 4, 5