Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 900
Yash Jaiswal Avatar asked Sep 07 '16 09:09

Yash Jaiswal


People also ask

How do you do a for-loop with multiple variables?

And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas. Do not forget to end the complete initialization statement with a semicolon.

Can I use multiple variables in for-loop Python?

Can you have 2 variables in a for loop Python? By using zip() and enumerate(), we can iterate with two variables in a for loop. We can also iterate with two elements in a dictionary directly using for loop.

How do you pass a two variable loop in Python?

How can I include two variables in the same for loop? t1 = [a list of integers, strings and lists] t2 = [another list of integers, strings and lists] def f(t): #a function that will read lists "t1" and "t2" and return all elements that are identical for i in range(len(t1)) and for j in range(len(t2)): ...


3 Answers

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)
like image 88
jhole89 Avatar answered Nov 14 '22 22:11

jhole89


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])
like image 32
Ananth Avatar answered Nov 14 '22 22:11

Ananth


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
like image 20
Ahsanul Haque Avatar answered Nov 14 '22 22:11

Ahsanul Haque