Nested list comprehension

19 August 2020

Code

# Create a list
x = [[1,2,3], [10,20,30]]

# Nested list comprehension:
y1 = [j/2 for i in x for j in i ]

# Output # 1:
print(y1)

Output # 1:


[0.5, 1.0, 1.5, 5.0, 10.0, 15.0]

.

# Nested list comprehension with 'if-else'
y2 = ['Yeah!' if(j%2==0) else '...' for i in x for j in i ]
print(y2)

Output # 2:


['...', 'Yeah!', '...', 'Yeah!', 'Yeah!', 'Yeah!']






Any errors in code above?
Please send a message.