1
records = [["chi", 20.0],["beta", 50.0],["alpha", 50.0]]
a = len(records)
for i in range(3):
    var = records[i]
print(var)

What I want to do is to create a different variable for each list (for instance there are three lists in records so i want to assign each list to a different variable (3 variables since there are three lists)). However, it only prints the last list(["alpha", 50.0]) and only one variable is assigned (var).

pfft khaganate
  • 111
  • 1
  • 10
  • 1
    Create a list and append results to it. – Maroun Mar 08 '21 at 11:57
  • 1
    Does this answer your question? [How do you create different variable names while in a loop?](https://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop) – DarrylG Mar 08 '21 at 11:59
  • @Maroun--how does"create a list and append results to it" answer OP's intent to "create a different variable for each list" (actually sublist--which is a bad idea)? OP should just use a dictionary with the keys as desired variable names and sublists as the values. – DarrylG Mar 08 '21 at 12:04
  • 1
    you should re-consider if that's what you really want to do, seems like a bad practice. But perhaps `var1, var2, var3 = records`. – avloss Mar 08 '21 at 12:04
  • You are assigning values inside a loop and printing outside. Value is assigned to same variable 3 times. So you are seeing last value result. You need 3 different variables or a list so that you can keep values of all three. – Amit Mar 08 '21 at 12:06
  • Please [edit] your question to clarify *exactly* what behaviour you desire. Do you want ``var`` to contain three results? Do you want three variables ``var1``, ``var2``, ``var3``? If you want the latter (as the question currently implies), then a) why *not* use a single variable of a list, and b) what behaviour do you expect when the loop iterations are not fixed? – MisterMiyagi Mar 08 '21 at 12:12

1 Answers1

2

because var is not appending anything it's just overwriting the value in Var but there isn't much point in appending it to separate lists as its all in one list already and everything is accessible by using

records[X][Y]

with X being the sublist location and Y being the value inside that sublist

and if you want this to be easier to use i'll suggest using dictionaries but this isn't necessary

epressoD
  • 136
  • 5