Python List (Part V)
smart and simple
List Comprehension
Well, now you all are very much familiar with lists in python and this will be the last article for the list.
Today we will see the list comprehension which is very interesting and will help us to save time while coding.
Let’s understand what it is.
suppose I have a list A = [2, 6, 8, 10] and I want a new list as B which will contain a square of elements that are present in list A
This is possible with for loop :
But for a developer, time is the most important thing so I want to perform this operation in a single line.
Is it possible if yes then how?
Yes, it is possible in python
This is how you should understand.
Now, if I want to store True if the number is even and False if the number is odd
what is the append part here, i.e i % 2 == 0 which returns True if a value is even and False if it is odd.
let’s perform this in a single line of code.
Now, instead of True and False what if I want actual even numbers….
In that case, we will write for loop like this
We just have to add a condition here.
let’s make it more interesting,
suppose, I want that if a number is even then it should store ‘pune ’and if a number is odd then it should store ‘mumbai’
we have to use if and else for that
that means we want ‘pune if number is even else mumbai’ means we can write this as “ ‘pune’ if i % 2 == 0 else ‘mumbai’ ”
you just have to think about what you want to perform else is easy.
Thanks for reading !!