create list with list comprehension python code example
Example 1: list comprehension python
# Make a List that contains the doubled values of a given list:
values = [2, 4, 6, 8, 10]
doubled_values = [x*2 for x in values]
print(doubled_values) # Outputs [4, 8, 12, 16, 20]
# You could achieve the same result like this:
values = [2, 4, 6, 8, 10]
doubled_values = []
for x in values:
doubled_values.append(x*2)
print(doubled_values)
Example 2: list comprehension in python
Squaring List elements:
By loop:
lst = [1, 2, 3]
l =[]
for i in lst:
lst.append(i*i)
print(l)
By List Comprehension:
lst = [1, 2, 3]
l = [x*x for x in lst]
print(l)