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]
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]
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"}]
How it worked?
each iteration the x will be checked with the condition and stored
Top comments (2)
Itโs one of those things you canโt stop using once you learn about them
Wow