-2

so I have a loop, and I want to call a variable for example name and add x from a loop to the end of the variable's name, so it looks like name0.

for example:

for x, var enumurate(something):
    name + x = something

it gives me out error.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Aleksas
  • 1
  • 3
  • 5
    Any time you think you need to do this, you should be using an array or dictionary, not dynamically-constructed variables. – Barmar Oct 11 '16 at 16:10
  • Use a container, such as a list or a dictionary, rather than trying to roll your own. – kindall Oct 11 '16 at 16:10
  • You could achieve something like that but please don't do it. Just don't do it. Variable variable names are the first step on your road to hell. – Matthias Oct 11 '16 at 16:12
  • I understand that it's bad, but it's neccesery for me, I save myself from repeating each line, any examples ? – Aleksas Oct 11 '16 at 16:15
  • No, I'm sure it's not necessary. Please learn about data structures like `list` and `dict`. They will do what you want, but in a much cleaner way. Maybe you could enhance your question by describing why you think you need variable variable names? – Matthias Oct 11 '16 at 16:18
  • Could you give me some examples Matthias ? – Aleksas Oct 11 '16 at 16:22
  • It is neccesery, sorry I can't give you the code, it will be very hard to understand and I want to keep stuff basic. – Aleksas Oct 11 '16 at 16:29
  • Read about [Dictionaries](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) in the tutorial. – Matthias Oct 11 '16 at 16:29

1 Answers1

0

What you ask is possible, but should not be done.

>>> foo = ['fee', 'fie', 'foe', 'fum']
>>> for i, val in enumerate(foo):
...     exec 'foo%s = %s' % (i, repr(val))
...
>>> foo3
'fum'
>>> foo[3]
'fum'

What you are asking for is a typical beginner error. Refering to the fourth item in foo as foo3 has no advantages over writing foo[3]. You can iterate over foo without having to know how many items it has. You can mutate foo if you like. You can refer to the last item in foo as foo[-1] without having to know it has four items. Also, the name foo3 is nonsensical. It tells the reader of the code nothing about why the items in foo are so important that they would need a name.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • I will try to replicate, I do for the last time need an erray off, variable1, variable2 for further in my code. – Aleksas Oct 11 '16 at 16:37
  • Also, I'm not a rookie, I'm working with networking, this simple thing keeping me from progressing. – Aleksas Oct 11 '16 at 16:39
  • No, it doesn't work, again, what I need is variable + variable = further code. – Aleksas Oct 11 '16 at 16:41
  • 1
    You mean *you think* you need a variable number of variables, and *you think* you are not a rookie. – kindall Oct 11 '16 at 18:55