How to add numbers in a list Python | Example code

  • by

Use append() function to add numbers in a list 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-in 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 into 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:

How to add numbers in a list Python

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.