Click here

Wednesday, September 19, 2018

Python - List comprehension

List comprehensions are a tool for transforming one list (any iterable actually) into another list. During this transformation, elements can be conditionally included in the new list and each element can be transformed as needed.

The basic syntax is
[ expression for item in list if conditional ]

This is equivalent to:

for item in list:
    if conditional:
        expression

Example
1)
x = 1
y = 1
z = 1

lis = []
lis = [ [i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if (i+j+k) != N]
print lis

Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Above is the nested for loop
2)
x = [i for i in range(10)]
print x

This will give the output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

No comments:

Post a Comment

Omicron - people gathers in crowd

Amidst omicron thread, people are gathered in crowd at markets and public places to buy their daily needs. Because of full lockdown at Sunda...