for-in Expression
This expression is used to create new sequence by iterating over the elements of other sequences. It does not modify the original sequences. It reduces for-in loop to a single line of code.
syntax
python
expression for element in sequence if condition
# if condition is optionalexample - list comprehension
create a new list (of positive numbers) from existing list. This is commonly known as list comprehension.
python
numbers = [-7, -5, -2, 0, 2, 5, 7, -10, -20]
positive_numbers = [ x for x in numbers if x > 0 ]
print(positive_numbers)
# [2, 5, 7]same could be achieved using for-in loop
python
numbers = [-7, -5, -2, 0, 2, 5, 7, -10, -20]
positive_numbers = []
for x in numbers:
if x > 0:
positive_numbers.append(x)example - set comprehension
create a new set from existing set where each element is incremented by 2
python
existing_set = {2, 4, 6}
new_set = { x + 2 for x in existing_set }
print(new_set)
# {4, 6, 8}example - dictionary comprehension
create a new dictionary from existing dictionary where each value of the element is multiplied by 2
python
scores = {
"John": 10,
"Jane": 20,
"Jack": 30
}
new_scores = { key: value * 2 for key, value in scores.items() }
print(new_scores)
# {'John': 20, 'Jane': 40, 'Jack': 60}example - using zip
create a dict from a tuple of scores and a list of names. make each score multiply by 2
python
scores = (10, 20, 30)
names = ("John", "Jane", "Jack")
grades = { name: score * 2 for score, name in zip(scores, names) }
print(grades)
# {'John': 20, 'Jane': 40, 'Jack': 60}zip is a built-in function that combines two sequences into a zip object which is an iterator of tuples.