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