Python Tutorial

Python List Comprehension Explained With Example

Understanding List Comprehension in Python

Iterables like tuples, strings, arrays, and lists are used to build new lists using list comprehensions.List comprehension in Python consists of brackets that carry the expression for each element, as well as a for loop that iterates across every element.

Example:

odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1]

print (odd_square)

Output:

[1, 9, 25, 49, 81]
Did you find this article helpful?