Use the append() function to add numbers in a list in Python. Syntax of adding a single number into a given list.
lst.append(numbers)
Python Example add numbers in a list
Simple example code.
Use list.append()
It will append new elements into a list.
a_list = [1, 2, 3]
new_num = 4
a_list.append(new_num)
print(a_list)
Output: [1, 2, 3, 4]
Use enumerate()
Use it if you have an iterable object to add a list. It will add value to the existing list number.
a_list = [1, 0, 0]
new_nums = [1, 2, 3]
for index, integer in enumerate(new_nums):
a_list[index] += integer
print(a_list)
Output: [2, 2, 3]
Add user input numbers to the list
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Sum of elements in given list is :", sum(lst))
Output:
Do comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.