Add elements to a list in a while loop in Python

This tutorial will discuss about unique ways to add elements to a list in a while loop in Python.

Table Of Contents

Add random elements to a list using a while loop

Create an empty list, then start a while loop, which runs till the size of list is 10. During each iteration of loop, fetch a new random number between 1 to 100 and add that to the list. Once the list has 10 random numbers, while loop will end.

Let’s see the complete example,

import random

listOfElements = []

# Loop till size of list is 10
while len(listOfElements) < 10:
    # fetch a random number between 1 to 100
    randomNum = int(random.random() * 100)
    # add random number to the list
    listOfElements.append(randomNum)

print(listOfElements)

Output

[65, 48, 72, 8, 80, 17, 7, 63, 17, 64]

Related Articles

We added 10 random elements in list using a while loop

Add a range of elements to a list using a while loop

Create a counter variable and assign value 1 into it. Then run a while loop till the counter value is less than 11. In each iteration of while loop, add the current value of counter in the list, and increment the value of counter by 1. When value of counter reaches 11, while loop ends. At that time there will be 10 elements in the list.

Let’s see the complete example,

listOfElements = []

counter = 1

# Loop till counter value is not 11
while counter < 11:
    # add current counter value to the list
    listOfElements.append(counter)
    # increment counter by 1
    counter += 1

print(listOfElements)

Output

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

We added 10 numbers in list using a while loop.

Summary

We learned a way to add elements into a list using a while loop. Thanks.

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