How to store values retrieved from a loop in different variables in Python?

33,844

Solution 1

Create a list before the loop and store x in the list as you iterate:

l=[]
for i in range(1,11):
    x = raw_input()
    l.append(x)
print(l)

Solution 2

You can store each input in a list, then access them later when you want.

inputs = []
for i in range(1,11);
    x = raw_input()
    inputs.append(x)


# print all inputs
for inp in inputs:
    print(inp)

# Access a specific input
print(inp[0])
print(inp[1])

Solution 3

You can form a list with them.

your_list = [raw_input() for _ in range(1, 11)]

To print the list, do:

print your_list

To iterate through the list, do:

for i in your_list:
    #do_something
Share:
33,844
Yash Jaiswal
Author by

Yash Jaiswal

Updated on September 27, 2020

Comments

  • Yash Jaiswal
    Yash Jaiswal over 3 years

    Just a quick question.
    Suppose, I have a simple for-loop like

    for i in range(1,11):
        x = raw_input() 
    

    and I want to store all the values of x that I will be getting throughout the loop in different variables such that I can use all these different variables later on when the loop is over.