DEV Community

Cover image for List Comprehension in Python
Felix DUSENGIMANA
Felix DUSENGIMANA

Posted on

List Comprehension in Python

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"]
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Let's understand clearly how list comprehension works.
The Syntax

fruits_with_letter_a= [expression for item in iterable if condition == True]
Enter fullscreen mode Exit fullscreen mode

Expression
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]
Enter fullscreen mode Exit fullscreen mode

Iterable
The iterable can be any iterable object, like a list, tuple, set etc.

Condition
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 )
Enter fullscreen mode Exit fullscreen mode

what will be the output🤔?

The answer
['p', 'h', 'e', 'l', 'i', 'x']
Enter fullscreen mode Exit fullscreen mode

Did you get it?


You now know more about list comprehension.

Read a lot via w3schools.com

Discussion (0)