DEV Community

Vishnu Vardhan Reddy
Vishnu Vardhan Reddy

Posted on

Python List Comprehensions

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]
Enter fullscreen mode Exit fullscreen mode
# squared elements
nums = [*range(1,11,1)]
print(nums)
squared_nums = [n*n for n in nums]
Enter fullscreen mode Exit fullscreen mode
# filtering even numbers
nums = [1,5,3,4,6,2,7,8]
even_nums = [n for n in nums if n%2 == 0]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)