2

I am new to Python so apologies in advance. Here is the code that I have problems with:

x = 1

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"

for x in range (1,11):
    print("v"+str(x))

This is the returned result:

v1
v2
v3
v4
v5
v6
v7
v8
v9
v10

And this is what I want the returned result to be:

First
Second
Third
Fourth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth

How could I print the content of increasingly named variables?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128

9 Answers9

3
for i in range(1, 11):
    print(locals()['v' + str(i)])

By the way, that's bad. Learn about dictionaries.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
3

Try this. Just store the strings in a list and print it:

x = 1
store_1 = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth","Tenth"] 
for x in store_1:
    print(x)
Mahir Islam
  • 1,941
  • 2
  • 12
  • 33
2

Instead of storing each value in it's own variable, I would suggest storing all of the values in a list:

Storing in a list -

v = ["First", "Second", "Third"...] 

To access the value in this list, you would use syntax similar to this (note that in python, lists start at index zero):

str = v[0]
# str will now be equal to "First"

Now when you use range, you'll generate a sequence of numbers that can be used as the index of your list:

for x in range (0,11):
    print(v[x])

So this loop will evaluate to print commands such as:

print(v[0]) # "First"
print(v[1]) # "Second"
print(v[2]) # "Third"
...

Accessing a list at a specific index will return the value stored at the same index.


Please note that I've changed range() to start at zero since if you start at 1 you'll be skipping the first element at index zero. In addition, this code could further be improved by using the length of the list as the "end" index for the range:

v = ["First", "Second", "Third"...] 
num_items = len(v)
for x in range(0, num_items):
    print(v[x])

Using this method, your v list can be different sizes and you won't need to make any changes to the loop.


A final note thanks to a helpful commenter: The range function actually uses zero as a default first value, so the loop could be simplified even further:

for x in range(num_items):
    print(v[x])
Lix
  • 47,311
  • 12
  • 103
  • 131
  • 1
    Very nice answer. `range()` starts at `0` by default. – RoadRunner Jul 11 '18 at 11:34
  • @RoadRunner - yes I was thinking of adding that at the end - thanks for the feedback! – Lix Jul 11 '18 at 11:35
  • Very detailed and esplicative for something OP hasn't asked about. – Marco Bonelli Jul 11 '18 at 13:29
  • @MarcoBonelli - I don't really understand what you mean. Would you mind expanding on that? – Lix Jul 11 '18 at 14:41
  • The question is about accessing different variables which have increasingly numbered names, it has nothing to do with lists, which is what you are suggesting. Hence, you are not answering OP's question. – Marco Bonelli Jul 11 '18 at 15:00
  • @MarcoBonelli The OP wanted to be able to access a bunch of variables while building the variable names "dynamically" - this can be clearly seen by the example code given. What I addressed in my answer is what I believed the OP wanted to **accomplish** - not *exactly* what they asked for because, as can be seen in other answers (including your own), what was originally asked for was the "bad way". – Lix Jul 11 '18 at 15:05
  • I know your intention, but that still doesn't change the fact that you didn't answer the question. You should first do so, *then* explain why using a list or dict is a better approach. At least IMHO. – Marco Bonelli Jul 11 '18 at 15:06
  • Ok - so that is where our approaches differ :) I don't really feel that showing the bad way to do it (because they asked for it) is the correct way to address scenarios like this. I'm not sure if it is relevant to this specific case, but the [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) comes to mind. – Lix Jul 11 '18 at 15:44
1

You have either the option to use locals as Marco pointed out or use eval like -

for i in range(1, 11):
    print eval("v{}".format(i))

But a better solution to this problem is to use list or dictionary

Sushant
  • 3,499
  • 3
  • 17
  • 34
1

Eval is also an option here

for i in range (10):
    print(eval('v{}'.format(i+1)))
Khanal
  • 788
  • 6
  • 14
1

Keep it simple, create list and iterate over using loop.

Numbers = ["First", "Second","Third","Forth", "Fifth", "Sixth","Seventh","Eighth", "Ninth", "Tenth"]

for number in Numbers:
    print number

Output:

First Second Third Fourth Fifth Sixth Seventh Eighth Ninth Tenth

Martin
  • 2,411
  • 11
  • 28
  • 30
0

You can use globals() to access global variables.

x = 1

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"

for x in range (1,11):
    print(globals()["v"+str(x)])

This outputs:

First
Second
Third
Forth
Fifth
Sixth
Seventh
Eighth
Ninth
Tenth
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

Use a list:

v1 = "First"
v2 = "Second"
v3 = "Third"
v4 = "Forth"
v5 = "Fifth"
v6 = "Sixth"
v7 = "Seventh"
v8 ="Eighth"
v9 = "Ninth"
v10 = "Tenth"
for x in [v1,v2,v3,v4,v5v6,v7,v8,v9,v10]:
    print(x)
whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44
  • This is just printing all values of a list - what the OP is looking for is a way to loop over a dynamic number of elements - as far as I understand :) – Lix Jul 11 '18 at 11:24
0

You could also store your items as key-value pairs in a dictionary:

lst = ["First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth","Tenth"]

d = {"v" + str(i+1): e for i, e in enumerate(lst)}
# {'v1': 'First', 'v2': 'Second', 'v3': 'Third', 'v4': 'Fourth', 'v5': 'Fifth', 'v6': 'Sixth', 'v7': 'Seventh', 'v8': 'Eighth', 'v9': 'Ninth', 'v10': 'Tenth'}

# print key -> value pairs
for v in d:
    print(v, "->", d[v])

Which gives the following mappings:

v1 -> First
v2 -> Second
v3 -> Third
v4 -> Fourth
v5 -> Fifth
v6 -> Sixth
v7 -> Seventh
v8 -> Eighth
v9 -> Ninth
v10 -> Tenth
RoadRunner
  • 25,803
  • 6
  • 42
  • 75