You may haven't heard of this, but you're going to love it👌. Wait what exactly is List comprehension🤔? well, list comprehension is technique used by python programmers to create list from the previous list. Yeah, you've got it now, let's see some examples, right.
let's say you have this list of fruits.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
and you want only fruits with letter "a" in the name. well, you might think of using for loop like this
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] fruits_with_letter_a=  for x in fruits: if "a" in x: fruits_with_letter_a.append(x) print(fruits_with_letter_a)
This works fine but there is another way of doing exactly the same thing with only one line of code.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"] fruits_with_letter_a= [x for x in fruits if "a" in x] print(fruits_with_letter_a)
Let's understand clearly how list comprehension works.
fruits_with_letter_a= [expression for item in iterable if condition == True]
is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list.
Example: Set fruits names in the new list to upper case
newlist = [x.upper() for x in fruits]
The iterable can be any iterable object, like a list, tuple, set etc.
The condition is like a filter that only accepts the items that valuate to True.
Let's try same challenge
name = "phelix" lettes_list = [letter for letter in name] print(lettes_list )
what will be the output🤔?
Did you get it?
['p', 'h', 'e', 'l', 'i', 'x']
Did you get it?
You now know more about list comprehension.
Read a lot via w3schools.com