1

I am using easygui to get a list of integers from the user. It outputs something like this:

fieldValues = [1,2]

I want to convert that list to:

var1 = 1
var2 = 2
ahd1601
  • 11
  • 1
  • 3

1 Answers1

0

(EDITED to explain my reasoning more clearly)

One reason why you might want to convert a list to variables is to make the code more self-documenting. A variable like password is easier to understand than fieldValue[3], for instance.

However, as @Blender suggested, it is probably better not to assign the elements of a list to individual variables.

One way to achieve both goals would be to refer to the elements of the list by name rather than by number. In other languages, you could use an enumerated variable (e.g. an enum in Java or C#). You could use the enum package in Python for a fully robust solution or you could do something like this:

username, password = range(2)
print(fieldValue[username])
Simon
  • 10,679
  • 1
  • 30
  • 44
  • 1
    Don't you think that's a little confusing? – Blender May 21 '13 at 23:49
  • 1
    @Blender: I agree it could be confusing with variable names like `var1` but, with more meaningful names that relate to the values being returned from the GUI, it could make the code more readable. I think `fieldValue[password]` is more maintainable than `fieldValue[3]`, for instance. – Simon May 21 '13 at 23:55
  • Regarding your update: `fieldValue[username]` isn't something I see very much in Python code. `username` alone would be good, but storing constants like that isn't common and can be misleading. – Blender May 22 '13 at 00:46
  • 1
    If you know enough about the list to define such variables to use as list indices, you could just write `username, password = fieldValue`. – chepner May 22 '13 at 02:48
  • @chepner: +1: Yes, that's a very good point. Indeed, Blender may have been making this point too, though it didn't click with me until now. – Simon May 22 '13 at 03:10