1

Let's assume that I wanna collect n lists as an input. What I used to do was:

l=[]
for i in range(n):
    row=map(int,raw_input().split())
    l.append(row)

And then I used to access those list by l[0],l[1],...,l[n].

Is there any more elegant way to do this? I mean like creating variables dynamically within the for loop with names like: row1,row2,...,rown ?

2
  • 4
    The way you are doing it now sounds better than having such variables. Commented Jun 12, 2013 at 20:29
  • The only thing really wrong here is using l as a variable name, as PEP8 warns, it looks too much like 1 in some fonts Commented Jun 12, 2013 at 20:35

3 Answers 3

2

Anytime you ask yourself how you could create dynamic variables, the answer is "use a dictionary".

l=dict()
for i in range(n):
    k='row%d'%(i,)
    l[k] = map(int, raw_input().split())
Sign up to request clarification or add additional context in comments.

4 Comments

There are no hashes, though; might as well use a list
Agreed, if the variable names are simply variations on an ordered list of integers. However, this answer just address how to use a dictionary with dynamically generated keys in place of a set of dynamically generated variables names.
Perhaps it would be more elegant as a dict comprehension
Probably. I still use Python 2.6, but even there I could write l=dict( ('row%d'%(i,), map(int, raw_input().split())) for i in range(n) or something even more elegant.
1

It might seem like a good idea at first, but once you've tried it you'll probably realise that polluting your namespace is inelegant

The usual way to create the list is this nested list comprehension

rows = [[int(j) for j in i] for i in raw_input().split()]

You can throw map in there if it's clearer to you

rows = [map(int, i) for i in raw_input().split()]

Then you have rows[0], rows[1]... etc which is not all that different to row0 row1... and is far more acceptable namespace wise

Comments

0

In my opinion, this is definitely the best way of storing an arbitrary number of integers. You really don't want to create variables on the fly, mainly because of how you use them later. For example, if you want to use number 23, you can easily do l[22] to get your number, and to take care of cases where <23 numbers were input:

try:
    print l[22]
except IndexError:
    print "No element 22!"

It would be much harder just using a different variable name to call a possibly undeclared variable.

Additionally, this way you can use len(l) to find out how many numbers you have, whereas with variables, you'd have to do something messy with locals() and it's not a great idea.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.