Python list comprehensions helps to write concise code for making new lists from existing lists.
Let's look at some basic examples to understand list comprehensions.
# doubling elements
nums = [1, 2, 3, 4]
doubled_nums = [n*2 for n in nums]
# squared elements
nums = [*range(1,11,1)]
print(nums)
squared_nums = [n*n for n in nums]
# filtering even numbers
nums = [1,5,3,4,6,2,7,8]
even_nums = [n for n in nums if n%2 == 0]
Top comments (0)