Python list comprehensions
List comprehensions are the lists that are created by using the lists or sequences that are already created. The Output of list comprehension is the list. List comprehension consists of brackets with an expression followed by a for clause, while expressions can be anything. In simple terms, we can put in all kinds of objects in lists. Here is the simple example which explains list comprehensions.
Python Code:
All letters in the word ‘Python’ is listed by using list comprehension. The Output is the list with all letters in word Python.
alphabets = []
for letter in 'python':
alphabets.append(letter)
print(alphabets)
Output:
[‘p’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]
List Comprehension using single line
List comprehension can be executed by single line code using for and in keywords.
Python Code:
x = [i for i in range(5)]
print(x)
Output:
[0, 1, 2, 3, 4]
Python Code:
double = [n*2 for n in x]
print(double)
Output:
[0, 2, 4, 6, 8]