Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use iterator as variable name in python loop

I've been wondering if there is a way to use an iterator as a variable name in a Python loop. For example, if I wanted to create objects v0, v1, v2, is there a way to do something like this:

for i in range(3):
    v + str(i) = i**2

I know the syntax is wrong, but the idea should be clear. Something equivalent to paste in R? Thanks much,

like image 699
mike Avatar asked Dec 16 '11 06:12

mike


People also ask

Does a for loop use an iterator variable?

The iterator (loop) variable is the variable which stores a portion of the iterable when the for loop is being executed. Each time the loop iterates, the value of the iterator variable will change to a different portion of the iterable.

What is the iteration variable in Python for loop?

In particular, friend is the iteration variable for the for loop. The variable friend changes for each iteration of the loop and controls when the for loop completes. The iteration variable steps successively through the three strings stored in the friends variable.

How do you change the variable name in each loop iteration Python?

You can't change the name of a variable. What you probably want to do is create new values with new names each time through the loop. You can technically do that by fiddling with globals or locals or attributes, but that's a really bad idea.

Can a variable be a for loop Python?

A Python for loop has two components: A container, sequence, or generator that contains or yields the elements to be looped over. In general, any object that supports Python's iterator protocol can be used in a for loop. A variable that holds each element from the container/sequence/generator.


1 Answers

The builtin method globals() returns a dictionary representing the current global symbol table.

You can add a variable to globals like this:

globals()["v" + str(i)] = i**2

FYI: This is the answer to your question but certainly not the recommended way to go. Directly manipulating globals is hack-solution that can mostly be avoided be some cleaner alternative. (See other comments in this thread)

like image 81
gecco Avatar answered Sep 24 '22 22:09

gecco