Python. Using nested if and for constructs in list, set, and dictionary generators

Using nested if and for constructs in list, set, and dictionary generators


Contents


1. Nested if and for constructs in list, set and dictionary generators. General concepts

In generators of lists, sets and dictionaries, you can use:

  • if constructs to filter the resulting data;
  • nested for constructs in order to traverse the required data.

 

2. Examples using the extended if statement
2.1. Form a dictionary based on two lists

Task. There are 2 lists L1 and L2 of the same length. Form a dictionary D in which the elements of the list L1 are the keys and the elements of the list L2 are the values. Include in the dictionary only those elements in which the keys are in the range [5; 10].

Solution.

# Dictionary generators and nested if statements

# Two lists are specified
numbers = [ 12, 8, 3, 10, 7, 19 ]
strings = [ '1', '22', '333', '4444', '55555', '666666' ]

# Create a dictionary in which the keys are within [5; 10]
D = { k:v for (k,v) in zip(numbers, strings) if ((k>=5) and (k<=10)) }

# Print the dictionary D
print(D)

Program result

{8: '22', 10: '4444', 7: '55555'}

 

2.2. Forming a set containing only even numbers

Task. A list of random numbers is given. On the basis of this set, form a set containing only even numbers.

Solution.

# Set generators and nested if statements
# 1. Include the random module
import random

# 2. Set the number of numbers
n = int(input("n = "))

# 3. Create a list of n numbers, each number within [1; 10]
L = [ random.randint(1, 10) for t in range(1, n+1) ]

# 4. Create a set with only paired elements
S = { x for x in L if x%2 == 0 }

# 5. Display the result
print("L = ", L)
print("S = ", S)

Program result

n = 12
L = [5, 9, 10, 4, 2, 4, 7, 10, 3, 6, 10, 2]
S = {10, 2, 4, 6}

 

2.3. Formation of a list based on two lists according to the condition

Task. There are two lists of strings L1 and L2. Based on these lists, create a third list L3 containing only strings longer than 3 characters.

Solution.

# List generators and nested if statements
# 1. Two lists specified
L1 = [ 'abc', 'abcd', '1232', '5555', '200', 'jk' ]
L2 = [ 'jklmn', 'jprst', 'aaa', '77' ]

# 2. Create a resulting list
# 2.1. Get a sublist of results based on the L1 list
ResL1 = [ item for item in L1 if len(item)>3 ]

# 2.2. Get sublist of results based on L2 list
ResL2 = [ item for item in L2 if len(item)>3 ]

# 2.3. Get the resulting list
ResL = ResL1 + ResL2

# 3. Display the result
print("ResL = ", ResL)

Program result

ResL = ['abcd', '1232', '5555', 'jklmn', 'jprst']

 

3. Examples using the nested for construct
3.1. Using nested for constructs in dictionary generators

The example demonstrates different ways to get a dictionary based on a dictionary generator with a nested for construct.

# Nested for constructs in dictionaries
# 1. Form a dictionary from a given range
D1 = { k : v for k in range(1, 4) for v in range(10, 13) }
print("D1 = ", D1)

# 2. Creating a dictionary from two other lists
D2 = { k : v for k in ['a', 'b', 'c'] for v in [7, 8, 9] }
print("D2 = ", D2)

Program result

D1 = {1: 12, 2: 12, 3: 12}
D2 = {'a': 9, 'b': 9, 'c': 9}

As follows from the result, not all possible variants of k:v pairs are attached to the dictionary. This is due to the fact that duplicates are not allowed in dictionaries.

 

3.2. Using nested for loops in set generators

The example demonstrates the use of nested for loops in set generators to accomplish the following tasks:

  • form a set that includes the sum of all possible values from the given lists;
  • create all possible character sets from two arbitrary strings.
# Set generators and nested for constructs

# 1. The 2 lists are specified
L1 = [ 1, 3, 5, 5, 7, 8, 9 ]
L2 = [ 3, 3, 4, 5, 6, 7, 8, 9 ]

# 2. Form a set that includes the sum of all possible values from the lists
S = { x + y for x in L1 for y in L2 }
print(S)

# 3. Generate a set of pairs from the values of a character set
S2 = { (x, y) for x in 'ab' for y in '12' }
print(S2)

Program result

{4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}
{('b', '2'), ('a', '1'), ('a', '2'), ('b', '1')}

 

3.3. Using nested for-loops in list generators

Demonstrates the use of a nested for construct in a list generator. The following tasks are being solved:

  • create a list, each element of which is the element-wise sum of two tuples;
  • based on two lists of strings, create a new list containing strings common to both lists.

 

# List generators and nested for constructions

# 1. Two tuples are specified
T1 = ( 7.2, 8.1, 3.5, 4.4, 2.9 )
T2 = ( 1.6, 0.8, 9.1, 3.3, 8.2 )

# 2. Create a list that is the element-wise sum of two tuples
L1 = [
    T1[p1]+T2[p2]
    for p1 in range(len(T1))
    for p2 in range(len(T2))
    if p1==p2
]

print(L1)

# 3. Generate a list containing strings that are the same in two lists S1, S2
S1 = [ '12', '34', '56', '23' ]
S2 = [ '78', '90', '12', '34', '77' ]

L2 = [
    S1[p1]
    for p1 in range(len(S1))
    for p2 in range(len(S2))
    if S1[p1]==S2[p2]
    ]

print(L2)

Program result

[8.8, 8.9, 12.6, 7.7, 11.1]
['12', '34']

 


Related topics