What is list comprehension python?
Answers
List Comprehension in Python :
- List Comprehension is a one statement expression in python that is used to create a list using an already existing list following a compact syntax.
- They can be used in an effective way, but are not much user friendly to understand. One needs to take minutes with lot of concentration to understand such expressions. So, if you are going to create bit lists, better to ignore this approach.
- Syntax : [expression for element in iterable if condition]
It is equivalent to the looping :
for element in iterable:
if condition:
expression
Where, in list comprehension, the iterable will be a list.
Example :
Printing the cubes of even numbers present in the range of 1 to 10.
Using list comprehension:
cubes = [x**3 for x in range(1,10) if x%2==0]
print(cubes)
or simply,
[x**3 for x in range(1,10) if x%2==0]
Output :
[8, 64, 216, 512]
Explanation :
Here, expression = x**3 which will be executed whenever the element in the list iterable ranging from 1 to 10, excluding 10, [1, 2, 3, 4 , 5, 6, 7, 8, 9] satisfies the condition of getting reminder 0 when divided by 2 as in i%2==0
In normal looping way, it is written as :
for x in range(1,10):
if x%2==0:
print(x**3)
or
l=[]
for x in range(1,10):
if x%2==0:
l.append(x**3)
print(x)
Learn more :
1. Write a list comprehension that builds a list of the even numbers from 1 to 10 (inclusive).
https://brainly.in/question/16086791
2. What is the difference between a python tuple and python list?
https://brainly.in/question/13319756