Lists in Python are ordered mutable sets of objects, numbered from 0. In this case, objects can be different – from integers to strings. Lists can also store lists in themselves.
In this article, we will understand the basic principles of lists in Python, and also consider the methods of working with them. If you’re learning Python from scratch, we suggest you also check out the Beginner’s Roadmap .
- Memory storage
- List creation
- Slices
- Simple operations
- List methods
Memory storage
When creating a list, an empty area is reserved in memory. On the one hand, this is no different from creating any other data type, but the difference is that the contents of the list can change:
numbers = [1, 2]
numbers[1] = 3
# обновлённый список: [1, 3]
Before replacing an element of the sequence, it print(numbers[1])
will output 2, and after replacing it – 3.
Creating a list in Python
This can be done in several ways, for example by listing the elements of the list in square brackets:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this case, the unit will be at position 0, that is, it print(numbers[0])
will display 1.
You can also use a function to handle an iterable object list()
. Let us have some line, then:
list('tproger')
# ['t', 'p', 'r', 'o', 'g', 'e', 'r']
There are also list generators that let you apply a given expression to each element in a sequence. Let’s say you need to create a list consisting of numbers from 1 to 5 inclusive:
numbers = [i for i in range(1,6)]
# [1, 2, 3, 4, 5]
Slices of the list
Slices allow you to get a subset of values. The following code will return a list with elements starting at index 0 and excluding index 2 and above:
numbers = [1, 5, 9, 6]
print(numbers[0:2])
# вывод [1, 5]
Next, let’s display everything, except for the element at position 3:
print(numbers[:3])
# вывод [1, 5, 9]
And now from index 1 to the end:
print(numbers[1:])
# вывод [5, 9, 6]
Python List Operations
x in l
–true
if the itemx
is in the listl
;x not in l
–true
if the element isx
absent inl
;l1 + l2
– combining two lists;l * n , n * l
– copies the list ofn
times;len(l)
– the number of elements inl
;min(l)
– the smallest element;max(l)
– the largest element;sum(l)
– the sum of the numbers in the list;for i in list()
– iterates over elements from left to right.
Python list methods
Index
Returns the position of the first matched item. The search for a match occurs from left to right. Example:
numbers = [1, 5, 9, 6, 1, 2, 1]
print(numbers.index(1))
# вывод 0: первая найденная единица на позиции 0
Count
This method counts how many times the specified value appears in the Python list:
numbers = [1, 5, 9, 6, 1, 2, 1]
print(numbers.count(1))
# вывод 3, потому что единица встречается 3 раза
Append
Adds the specified value to the end:
numbers = [1, 5, 9, 6]
numbers.append(3)
# обновлённый список: [1, 5, 9, 6, 3]
Sort
Sorts the list in Python. By default, from smallest to largest:
numbers = [1, 5, 9, 6]
numbers.sort()
# обновлённый список: [1, 5, 6, 9]
You can also sort the sequence of elements from largest to smallest:
numbers = [1, 5, 9, 6]
numbers.sort(reverse = true)
# обновлённый список: [9, 6, 5, 1]
Insert
Inserts an element before the specified index:
numbers = [1, 5, 9, 6]
numbers.insert(3, [2, 3])
# обновлённый список: [1, 5, 9, [2, 3], 6]
Remove
Removes the first occurrence of an item in the Python list:
numbers = [1, 5, 9, 6, 1, 2, 1]
numbers.remove(1)
# обновлённый список: [5, 9, 6, 1, 2, 1]
Extend
Similar to the method append()
, it adds elements, but the advantage of the method extend()
is that it also allows you to add lists:
numbers = [1, 5, 9, 6]
numbers.extend([2, 3])
# обновлённый список: [1, 5, 9, 6, 2, 3]
Pop
And this method removes the element at the specified index, and also displays the deleted element. If no index is specified, the default method will remove the last element:
numbers = [1, 5, 9, 6]
numbers.pop(1)
# получаем:
# 5
# [1, 9, 6]
Join
Converts the list to a string. The element separator is written in quotes before the method, and the Python list itself must consist of strings:
mylist = ['сайт', 'типичный', 'программист']
print(', '.join(mylist))
# вывод 'сайт, типичный, программист'