rakesh kumar

Posted on

# Python List Comprehension

Python List Comprehension
Python is known for helping us produce code that is elegant, simple to write, and reads almost as well as plain English. List comprehension is one of the language's most distinguishing features, allowing us to develop sophisticated functionality with just one line of code. On the other hand, many Python writers struggle to fully utilize the more complex aspects of list comprehension. Sometimes programmers may overuse them, resulting in much less efficient and difficult-to-read code.

Using List Comprehension
newlist = [expression for item in iterable if condition == True]

Here we are showing basic use of list comprehension.

Code

``````#using for loop to iterate through items in list
numbers = [3, 5, 1, 7, 3, 9]
num = []

for n in numbers:
num.append(n**2)

print(num)
``````

Output:

``````[9, 25, 1, 49, 9, 81]
``````

All of this can be accomplished with only single line of code using list comprehension.

Code

``````#using list comprehension to iterate through list items
numbers = [3, 5, 1, 7, 3, 9]

num = [n**2 for n in numbers]

print(num)
``````

Output:

``````[9, 25, 1, 49, 9, 81]
``````

Using List Comprehension to Iterate through String
List comprehension can be used in case of strings also as they are iterables too.

Code

``````letters = [ alpha for alpha in 'javatpoint' ]
print( letters)
``````

Output:

``````['j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't']
``````

Using Conditions in List Comprehension
Conditional statements can be used by list comprehensions to change existing lists (or other tuples). We'll make a list with mathematical operators, numbers, and a range of values.

Code

``````number_list = [ num for num in range(30) if num % 2 != 0]
print(number_list)
``````

Output:

``````[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29]
``````