DEV Community

Cover image for List comprehensions in python
Shuhaib S
Shuhaib S

Posted on

4

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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay