list comprehension python using range code example
Example 1: python list comprehension
nums = [4, -7, 9, 1, -1, 8, -6]
half_of_nums = [x/2 for x in nums] #[2, -3.5, 4.5, 0.5, -0.5, 4, -3]
#optionally you can add an if statement like this
half_of_positive_nums = [x/2 for x in nums if x>=0] #[2, 4.5, 0.5, 4]
Example 2: 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)