For loop vs List comprehension

 In python, same result can be accomplished by writing the code in different ways. We can use whichever code we are more comfortable with. 

But while working in a company, if there are people who feel comfortable writing the code in different ways, then it is important for us to know different ways of writing a code as you may have to read someone else's code who is not used to write it your way!

Let's check by an example:

A simple for loop code is...

fruits = ['orange', 'mango', 'pineapple']

For getting the same result, we can also write it using list comprehension



For getting this result, we need not to assign the list to anything. But if we want to, we can do that too.




We can also slice the list


Or even use conditions inside the list


Another conditional expression



No comments:

Post a Comment

Complex query example

Requirement:  You are given the table with titles of recipes from a cookbook and their page numbers. You are asked to represent how the reci...