Python: List Comprehension

July 2, 2024

Main topic

List Comprehension create a new list in current list or iterable (list, tuple, set, string, dictionary, range, generator).

[expression for item in iterable if condition]

Example: we want new list with double item's value

numbers = [1,3,5]

doubled = [num * 2 for num in numbers]

Another example

friends = ["Rolf","Sam" , "Samantha", "Saurabh","Jen"]

starts_s = [friend for friend in friends if friend.startswith("S")]

Add 'friend' in friends if friend.startswith("S")

Is there anything else fun today?

I'm back to write this note. I must make it a habbit to do it every day.

Keywords: