Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python doubling all numbers in a list

Python doubling all numbers in a list

Document Object Reference Manual Python3 Examples

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

print

(

doubled_numbers

)

Code analysis:

  1. numbers = [1, 2, 3, 4, 5]: define a list containing numbers.
  2. doubled_numbers = [num * 2 for num in numbers]: use a list comprehension to iterate over numbers each element in the list num, and multiply it by 2 to generate a new list doubled_numbers。
  3. print(doubled_numbers): output the doubled list.

Output result:

[2, 4, 6, 8, 10]

Document Object Reference Manual Python3 Examples