Advanced Python

List Comprehension, an interesting topic for developers and interviewers. It allows a developer to write concise and readable code.

Let’s deep dive into this topic to use it more in our programming.

Syntax

[an expression one or more for loop optionally one or more conditions]

Let’s do some hands-on a few examples.

i) Find square of numbers:

a) Using a loop


a=[1,2,3]
b=[]
for i in a:
k=i*i
b.append(k)
print(b)
[1, 4, 9]

b) Using List Comprehension

a=[1,2,3]
k=[i*i for i in a]
print(k)
[1, 4, 9]

ii) find odd of numbers using List Comprehension and without List Comprehension

a) Using a loop

n=[21,102,56,33,99,101,36,33]
k=[]
for i in n:
if i%2!=0:
k.append(i)
print(k)
[21, 33, 99, 101, 33]

b) Using List Comprehension

n=[21,102,56,33,99,101,36,33]
k=[i for i in n if i%2!=0]
print(k)
[21, 33, 99, 101, 33]

Thank you for reading, hope you have enjoyed this!!