Add elements to list using for loop in Python

This tutorial will discuss about unique ways to add elements to list using for loop in Python.

Table Of Contents

Add elements to empty list using a for loop

Manytimes we encounter a situation where we need to add or append multiple elements into a list, and we want to do that in a loop. Consider a scenario, where we have an empty list, and we want to add 10 numbers in it. These numbers can be from 0 to 9. For that, first we will create an empty list, then we will iterate through a range of numbers from 0 to 10, and add them one by one into the list.

Let’s see the complete example,

# create an empty list
listOfNumbers = []

# Iterate over a range of numbers from 0 to 10
for i in range(10):
    # Add each number to list
    listOfNumbers.append(i)

print(listOfNumbers)

Output

Advertisements
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Related Article

It added 10 numbers into the list, using a for loop.

Add elements to a list using a for loop

In this example, first we will create a list with some numbers. Then we will iterate through a range of numbers i.e. from 14 to 19 using a for loop, and add them one by one into the list during the loop.

Let’s see the complete example,

# create a list
listOfNumbers = [11, 12, 13]

# Iterate over a range of numbers from 14 to 19
for i in range(14, 20):
    # Add each number to list
    listOfNumbers.append(i)

print(listOfNumbers)

Output

[11, 12, 13, 14, 15, 16, 17, 18, 19]

It added a range of numbers into the list, using a for loop.

Summary

We learned to add elements to list in a for loop.

Advertisements

Thanks for reading.

Leave a Comment

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.

Scroll to Top