DEV Community

Cover image for List comprehensions in python
Shuhaib S
Shuhaib S

Posted on

List comprehensions in python

List in python

Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuples, Set, and Dictionary, all with different qualities and usage.

How to mutate the value and set the new value in list?

nums = [1,2,3,4]

## we can double this value with 2 ( num *2 ) 

doubled = [x * 2 for x in nums ]

## output is : [2, 4, 6, 8]
Enter fullscreen mode Exit fullscreen mode

How it worked?
each iteration the x will be stored as calculated with 2

How to filter the list?

nums = [1,2,3,4]

## we can double this value with 2 ( num *2 ) 

filtered = [x  for x in nums if x > 2]

## output is : [3, 4]
Enter fullscreen mode Exit fullscreen mode

How it worked?
each iteration the x will be checked with the condition and stored

How to filter the List of dictionaries?

names = [
{"name":"abil"}, {"name":"john"},{"name":"willing"},{"name":"sam"}
]

## we can double this value with 2 ( num *2 ) 

filtered_names = [item  for item in names if item.startswith("s")]

## output is : [{"name":"sam"}]
Enter fullscreen mode Exit fullscreen mode

How it worked?
each iteration the x will be checked with the condition and stored

Top comments (2)

Collapse
 
chiragagg5k profile image
Chirag Aggarwal

Itโ€™s one of those things you canโ€™t stop using once you learn about them

Collapse
 
muhseenat profile image
Muhseena T

Wow