Lists in Python are ordered mutable collections of objects arbitrary types. Unlike an array, the type of objects can be different. Similar to an array, list elements are enclosed in square brackets []. For In order to work with the list, it must be specified.
Creating a list
There are several ways to set a list: You can process any iterable object with the built-in list function
Code: Create List
c = list('Python')
print(c)
# ['P', 'y', 't', 'h', 'o', 'n']
# The list can be specified using a literal, i.e., filled in manually.
c = [] # empty list
c1 = [1, 2, 3] # the list contains 3 numbers
print(c)
print(c1)
# []
# [1, 2, 3]
Lists can be iterated using loops. General form:
Code: iterate list
l = [1, 2, True, None, "Python"]
for i in l:
print(i)
# 1
# 2
# True
# None
# Python
Lists can be generated using loops.
Code: list generates using loop
# << expression >> for << variable >> in << sequence >>
# Let's fill the list with numbers in order from 1 to 10
s1 = [i for i in range(1, 11)]
print(s1)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Fill the list with 5 random numbers from the range from 1 to 10 inclusive.
Code: Example generate random list
import random
n = 5
s = [random.randint(1, 10) for i in range(n)]
print(s)
# [7, 6, 5, 3, 1]
Lists can be filled out from the keyboard after starting the program
As a result, the list will be filled with the entered elements and displayed on the screen.
Code: Example generate random list
s1 = [int(input('Enter a list item: ')) for i in range(1, 11)]
# Enter a list item: 1
# Enter a list item: 2
# Enter a list item: 3
# Enter a list item: 4
# Enter a list item: 5
# Enter a list item: 6
# Enter a list item: 7
# Enter a list item: 8
# Enter a list item: 9
# Enter a list item: 10
print(s1)
# [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# But you won't be able to fill out the list from the keyboard like this:
s1 = []
for i in range(0, 10):
s1[i] = int(input('Enter a list item: '))
# Enter a list item: 1
# IndexError: list assignment index out of range
All elements of the list are numbered in order from 0 to n-1, where n is the number elements in the list. Unlike strings, lists can be accessed by index elements of the list - both to obtain its value and to change it. In lines By index you can only get the character of the string, but you cannot change it.
Getting the value of a list element by its number.
Getting a list element by number, similar to working with an array in others programming languages. We indicate the name of the list, and in square brackets it number. The numbering of list elements starts from 0.
Code: list index
s = [1, 2, 3, 4, 5]
print(s[1])
# 2
# Let's say we need to add elements of the list
# that are in zero and second place.
s = [1, 2, 3, 4, 5]
a = s[0] + s[2]
print(a)
# 4
# The index can also be a negative number, then the numbering goes
# from right to left: -1 -2 -3..., etc. it does not start from 0.
s = [1, 2, 3, 4]
print(s[0])
print(s[-1])
# 1
# 4
Slices in lists allow, just like in strings, to extract more than one element, but a group of elements. The syntax is exactly the same as in strings list[start:end:step].
Code: Slicing in lists
a = [1, 2, 3, 4, 5, 6, 7]
print(a[1]) # 2
print(a[1:]) # [2, 3, 4, 5, 6, 7]
print(a[1:4]) # [2, 3, 4]
print(a[1:5:2]) # [2, 4]
print(a[:3]) # [1, 2, 3]
Changing the value of a list element by its number Changing a list item by number works the same way as changing array element in other programming languages. General view looks like in the following way:
list[< item number >] = < new value >
Code: Slicing in lists
s = [1, 2, 3, 4, 5]
print(s)
s[1] = 'New value'
print(s)
# [1, 2, 3, 4, 5]
# [1, 'New value', 3, 4, 5]
Iterating through list elements, as well as filling it, can be done using a cycle.
Code: Iterating over elements in a list
a = [1, 2, 5, 6, 7]
for i in a:
print(i, end=' ')
# 1 2 5 6 7
'''
iterate through all the elements
of the list and change them, then
here you can use the range function
'''
a = [1, 2, 5, 6, 7]
for i in range(len(a)):
a[i] += 1
print(a)
# [2, 3, 6, 7, 8]
'''
You can also iterate through
and change elements using a while loop
'''
a = [1, 2, 5, 6, 7]
i = 0
b = len(a)
while (i < b):
a[i] *= 2
i += 1
print(a)
# [2, 4, 10, 12, 14]
List elements can be processed using standard built-in functions Python such as
Code: min()
a = [8, 2, 3, 2, 5]
print(min(a))
# 2
a = [8, 2, 3, 2, 5]
print(max(a))
# 8
a = [1, 3, '0']
print(min(a))
# TypeError: '<' not supported between instances of 'str' and 'int'
Code: len()
a = [8, 2, 3, 2, 5]
print(len(a))
# 5
Code: append()
a = [1, 2, 3]
a.append('list')
print(a)
# [1, 2, 3, 'list']
Code: extend()
a = [1, 2, 3]
b = [0, 5]
a.extend(b)
print(a)
# [1, 2, 3, 0, 5]
Code: insert()
a = [1, 2, 3]
a.insert(1, 'list')
print(a)
# [1, 'list', 2, 3]
Code: remove()
a = [1, 2, 3, 2, 5]
print(a.remove(2))
print(a)
# [1, 3, 2, 5]
Code: pop()
a = [1, 2, 3, 2, 5]
print(a.pop(2))
print(a)
# 3
# [1, 2, 2, 5]
Code: index()
a = [1, 2, 3, 2, 5, 6, 2, 5, 7, 2]
print(a.index(2, 2, 4))
# 3
Code: count()
a = [1, 2, 3, 2, 5, 6, 2, 5, 7, 2]
print(a.count(2))
# 4
Code: sort()
a = [1, 2, 3, 2, 5, 6, 2, 5, 7, 2]
a.sort()
print(a)
# [1, 2, 2, 2, 2, 3, 5, 5, 6, 7]
Code: reverse()
a = [1, 2, 3]
a.reverse()
print(a)
# [3, 2, 1]
Code: copy()
a = [1, 2, 3]
b = a.copy()
print(b)
# [1, 2, 3]
Code: clear()
a = [1, 2, 3]
a.clear()
print(a)
# []
Methods designed to change the value list, the list itself is changed, and the result of the method does not need to be assigned any variable.
Code: Methods designed
a = [1, 4, 2, 3]
a.sort()
print(a)
# [1, 2, 3, 4]
a = a.reverse()
print(a)
# None
In Python, in addition to the usual one-dimensional lists, they also use multi-dimensional lists. Most often these are two-dimensional lists. Multi-dimensional lists are also called nested lists. Nested elements can also be other data types, for example, tuples, dictionaries, etc.
A multi-dimensional list is defined as follows:
a = [ [ ], [ ], [ ], ... , [ ] ]
Code: multi-dimensional list
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# or
a = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(a[1][1])
print(a[0][2])
# 5
# 3
print(a[1])
# [4, 5, 6]
print(a)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
A tuple is a sequence of immutable objects. Tuples are very similar to lists. The difference is that:
- elements of a tuple cannot be changed;
- use regular parentheses instead of square brackets.
The advantage of a tuple over a list is that it takes up less places in memory.
Processing tuple elements A tuple is created either by simply assigning elements separated by commas, or indicating them in brackets, but also separated by commas.
Code: tuple()
a = ('tuple', 'Python', 3, 0)
b = (1, 2, 3, 4)
c = 'a', 'b', 'c'
# empty tuple
a = ()
print(a, type(a))
# () < class 'tuple' >
t = tuple('Python')
print(t)
# ('P', 'y', 't', 'h', 'o', 'n')
# Filling a tuple with random numbers
import random
t1 = tuple([random.randint(1, 10) for i in range(1, 11)])
print(t1)
# (1, 2, 7, 8, 4, 10, 2, 4, 9, 5)
# Fill a tuple of 10 elements with powers of two from 1 to 10
t2 = tuple([pow(2, i) for i in range(1, 11)])
print(t2)
# (2, 4, 8, 16, 32, 64, 128, 256, 512, 1024)
In order to get some element of the tuple, you need to access it by index, indicating it in square brackets [ ].
a = (1, 2, 3, 4)
print('a[1] =', a[1])
# a[1] = 2
'''
Let's get a range of elements
from a tuple, then use a slice
'''
a = (1, 2, 3, 4)
print('a[1:3] =', a[1:3])
# a[1:3] = (2, 3)
'''
Let's try to replace a tuple element by index
'''
a = (1, 2, 3, 4)
a[1] = 0
# TypeError: 'tuple' object does not support item assignment
a = (1, 2, 3, 4)
# Convert tuple to list
a_list = list(a)
# Modify the element at index 1
a_list[1] = 0
# Convert modified list back to tuple
a = tuple(a_list)
print(a)
# Output: (1, 0, 3, 4)
All operations that are defined on lists are defined on tuples. but not changing list elements. We present some in the form of a table
A tuple is an immutable subsequence. But still, sometimes there is a need to change it, and then proceed as follows: create a new tuple with some elements from the old and adding new ones.
Function, Method | Description | Example |
---|---|---|
len() | Length of a tuple (number of elements). |
a = (1, 2, 3, 5, 8) print(len(a))Output: 5 |
+ | Concatenation (joining) of tuples. |
a = (1, 2, 5) b = (3, 4) c = a + b print(c)Output: (1, 2, 5, 3, 4) |
in | Element membership in a tuple, returns True if the element is present, otherwise False. |
a = (1, 2, 3, 4) print(2 in a)Output: True |
max() | Finds the maximum element in a tuple. Works only if all elements of the tuple are of the same type. |
a = (1, 0, 0.3) print(max(a))Output: 1 b = ('f1', '3f', 'f2') print(max(b))Output: f2 a = (1, '0', 0.3) print(max(a))Output: Error |
min() | Finds the minimum element in a tuple. Works only if all elements of the tuple are of the same type. |
a = (1, 0, 0.3) print(min(a))Output: 0 b = ('f1', '3f', 'f2') print(min(b))Output: 3f a = (1, '0', 0.3) print(min(a))Output: Error |
Code: tuple()
a = (1, 2, 3, 5, 8)
print(len(a))
# Output: 5
a = (1, 2, 5)
b = (3, 4)
c = a + b
print(c)
# Output: (1, 2, 5, 3, 4)
a = (1, 2, 3, 4)
print(2 in a)
# Output: True
a = (1, 0, 0.3)
print(max(a))
# Output: 1
b = ('f1', '3f', 'f2')
print(max(b))
# Output: f2
a = (1, '0', 0.3)
print(max(a))
# Output: TypeError: '>' not supported between instances of 'str' and 'int'
The zip() function is designed to combine elements of iterable sequences into tuples according to the following rule: the first elements of all sequences specified as arguments are combined into the first tuple, the second elements into the second tuple, and so on. The process stops when the end of the shortest sequence is reached. Typically, for convenience in further work, all resulting tuples are combined into a sequence (list, tuple, dictionary, set). The iterable sequences used as arguments in a single zip() function can be of different types.
Code: zip()
a = 'string' # string
b = [1, 'a', 2] # list
c = ('Tuple', 'from', 'some', 'words') # tuple
d = list(zip(a, b, c)) # get a list of tuples
d1 = tuple(zip(a, b, c)) # get a tuple of tuples
print(d)
print(d1)
# Output:
# [('s', 1, 'Tuple'), ('t', 'a', 'from'), ('r', 2, 'some')]
# (('s', 1, 'Tuple'), ('t', 'a', 'from'), ('r', 2, 'some'))
The enumerate() function is used to simplify iterating over elements iterable sequences, when you need to get them along with the elements indexes. The result of the function is a tuple consisting of two elements – element index and its value
Code: enumerate()
a = [2, 4, 6]
for i in enumerate(a):
print(i)
# (0, 2)
# (1, 4)
# (2, 6)
'''
When processing all elements of a sequence
instead of a combination range(len()) may be
more convenient to use the enumerate() function.
'''
a = [2, 4, 6]
for i in range(len(a)):
print(i, a[i])
# 0 2
# 1 4
# 2 6
a = [2, 4, 6]
for i, val in enumerate(a):
print(i, val)
# 0 2
# 1 4
# 2 6