List processing in loops. Generating lists using list generators. Iteration through the lists. Presentation and processing matrices using lists. Operation in

List processing in loops. Generating lists using list generators. Iteration through the lists. Presentation and processing matrices using lists. Operation in


Contents



1. Examples of using for and while loop statements with lists
1.1. Creating a list using a while loop. Fibonacci Series Formation

In the example, a list of Fibonacci numbers is formed. Each number in the Fibonacci series is the sum of the two previous numbers. The program uses the following variables

  • Max – the maximum value of the number in the series;
  • A – the resulting list of numbers;
  • x1, x2, x3 – additional variables.

The text of the program is the following

# Creating a list using a while loop
# Fibonacci series from 1 to 100
Max = 100
x1 = 1
x2 = 1
x3 = x1+x2
A = [x1,x2,x3] # create a list of numbers

while x3<=Max:
    x1=x2
    x2=x3
    A+=[x2]
    x3=x1+x2

print("A = ",A)

The result of the program

A = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

 

1.2. Search for an item in a list using a for loop

The example determines the position of the specified item in the list of strings. If the item is not in the list, then after the search the position value is -1.

# Search for a string in an array of strings
# Given a list of strings
L = [ 'abc', 'bcd', 'def', 'abd', 'bcd', 'hef', 'inn' ]

s = str(input("Input string:")) # s - search string
pos=-1 # position
k=0 # current position in the loop

for t in L: # loop traversal
    if s==t:
        pos=k
        break
    k=k+1

print("pos = ",pos)

The result of the program

Input string:inn
pos = 6

 

1.3. Formation of a new list from the existing one using the for operation. Reversing of the list

The example reverses the specified list A. The result is written into the list B.

# Reversing of the list
# The specified list
A = [ 2.3, 'a', "abcde", -1220, True, False ]
B = [] # The resulting list

for a in A:
    B = [a] + B

print("A = ", A)
print("B = ", B)

The result of the program

A = [2.3, 'a', 'abcde', -1220, True, False]
B = [False, True, -1220, 'abcde', 'a', 2.3]

 

2. What are list generators? Examples

A list generator is a Python language tool that allows you to form another list from an existing list. Elements of another list can be formed by some expression (for example, increase by 10).

For more information about the features of using list generators, see the topic:

 

2.1. An example of generating a list from a character string
# List generators
# generate list A from the string 'Hello'
A = [i for i in 'Hello'] # A =   ['H', 'e', 'l', 'l', 'o']
print("A = ", A)

The result of the program

A = ['H', 'e', 'l', 'l', 'o']

 

2.2. An example of generating a list from a string of characters using the specified expression

In the case of generating a list, you can set special conditions for creating each item in the list. In the previous paragraph 2.1 a list was generated from the string. In the following example, each character from a string is duplicated 3 times:

# List generators
# generate the list A from the string 'Hello', the character c is duplicated 3 times
A = [c*3 for c in 'Hello'] # A = ['HHH', 'eee', 'lll', 'lll', 'ooo']
print("A = ", A)

As can be seen from the above code, each element of the new list is formed on the basis of a certain regularity – a certain expression. In this case, it is a tripling c*3 of each element (symbol) in the list.

A = [c*3 for ... ]

The expression with which the elements in the newly-formed lists are obtained can be any, depending on the task.

The result of the program

A =   ['HHH', 'eee', 'lll', 'lll', 'ooo']

 

2.3. An example of generating a list of integers
# Creating a new list using a list generator
# Create a list of 5 items
L = list(range(5)) # L = [0, 1, 2, 3, 4]

# list generator: multiply each list item L by 2
L2 = [t*2 for t in L] # L2 = [0, 2, 4, 6, 8]

print("L = ", L)
print("L2 = ", L2)

The result of the program

L =   [0, 1, 2, 3, 4]
L2 = [0, 2, 4, 6, 8]

 

3. Iterations through the lists. Examples

To iterate through the list in Python, the for loop operator is best suited.

For more information about using iterators to bypass lists, see the topic:

 

3.1. An example of calculating the sum of the elements of the list using iteration through the list
# Iteration through the list
# The specified list
A = [ 1, 2, 5, -4, 4, 10 ]

# calculating the sum of the items of the list
s = 0

for t in A: # iteration through list A
    s = s + t

print("A = ", A)
print("Summ = ", s)

The result of the program

A = [1, 2, 5, -4, 4, 10]
Summ = 18

 

3.2. An example of calculating the sum of elements of a two-dimensional matrix using iteration through the list

In the example, the sum of the elements of the two-dimensional matrix M is calculated by traversing the list.

# Iteration through lists
# Traversal of the matrix of real numbers

# Given matrix of size 3 * 4
M = [
    [ 5.2, 2.8, 1.1, 4.4 ],
    [ 0.8, 2.3, 8.4, 5.0 ],
    [ 1.1, 3.2, 5.5, 1.0 ],
    ]

# calculation of the sum of matrix elements whose value is greater than 5.0
s = 0
for m in M:
    for n in m:
        if n>5.0:
            s += n

print("M = ", M)
print("Summ = ", s)

The result of the program

M = [[5.2, 2.8, 1.1, 4.4], [0.8, 2.3, 8.4, 5.0], [1.1, 3.2, 5.5, 1.0]]
Summ = 19.1

 

4. Check for entry in the list. Operation in. Examples
4.1. An example of defining a given item in the list using the in operation

The example uses the in operation to fill the value of the logical variable b.

# Operation in - determining whether an item is in the list
A = [ 'abc', 7, 8.5, -100 ]

# Use of operation in
item = 8.5 # item to find
b = item in A # b = true

print("b = ",b)

The result of the program

b = True

 

4.2. An example of determining the presence of an element in a matrix using the in operator and for, if statements

The example determines the presence of a given character in a given matrix. The program displays the corresponding message.

The text of the program is as follows:

# The in operation - determining the presence of an element in the matrix
# specified matrix
Matrix = [ [ 'a', 'c', 'f', ';' ],
           [ 'z', 't', 'd' ],
           [ 'x', 'k' ]
         ]

symbol = str(input("Input symbol: "))

f_is = False
for row in Matrix:   # moving through nested lists (rows)
    if symbol in row: # operation in
        f_is = True
        break

if f_is:
    print("The symbol is in the matrix")
else:
    print("Symbol is not present in the matrix ")

The result of the program

Input symbol: x
The symbol is in the matrix

 


Related topics