Python doubling all numbers in a list
In Python, we can quickly double all numbers in a list using a list comprehension. A list comprehension is a concise and efficient way to create a new list.
Example
Original list
numbers
=
[
1
,
2
,
3
,
4
,
5
]
Use a list comprehension to double each number in the list
doubled_numbers
=
[
num *
2
for
num
in
numbers
]
Output result
(
doubled_numbers
)
Code analysis:
numbers = [1, 2, 3, 4, 5]: define a list containing numbers.doubled_numbers = [num * 2 for num in numbers]: use a list comprehension to iterate overnumberseach element in the listnum, and multiply it by 2 to generate a new listdoubled_numbers。print(doubled_numbers): output the doubled list.
Output result:
[2, 4, 6, 8, 10]
Python3 Examples