-2

How can I separate values from a multi-dimensional list, and assign them to individual variables using a for-loop? ( Without knowing the number of lists in the list ).

list = [ [ 1 , 2 ] , [ 3 , 4 ] , [ 5 , 6 ] , [ 7 , 8 ] , [ 9 , 10 ] ]
list1 = [ ]
list2 = [ ]
list3 = [ ]

for i in range(len(listA)):
    list1.append(listA[0]) 

output list1:

[ 1 , 2 ]

output list2:

[ 3 , 4 ]
Tony Stark
  • 71
  • 1
  • 2
  • 9
  • Do you have one list containing other lists? If so, do you want to store the inner lists as variables instead? If that's it, I can give a complete answer, with a for loop, but I don't think a loop is a good idea. – Andreas is moving to Codidact Oct 28 '17 at 20:21
  • Yes, I am trying to store the inner lists into separate varibles. I decided to use a for loop in my program to count the number of lists within a list and separate them. – Tony Stark Oct 28 '17 at 20:28
  • I've given you an answer I think tells you what you need. :) – Andreas is moving to Codidact Oct 28 '17 at 20:41
  • 3
    Why is "list1" better than "list[0]", which already works as-is? Trying to have a variable number of variables is a bad sign. – Ned Batchelder Oct 28 '17 at 20:50
  • @NedBatchelder There are different purposes for this. The code submitted in this question, might be different from the actual code. As these variables may contain different kind of information, it might be natural to separate them. Going `list -> variables` might produce faster code, as getting a variable is faster than getting a value from a list. – Andreas is moving to Codidact Oct 28 '17 at 20:54
  • 2
    @Andreas we can guess all we want, but making a variable number of variables is not a good idea. How will they be used later? You can't write lines of code that say "list47" in them, since you don't know how many there are. So you will then be accessing them via some kind of indirection? It's bad all around. This should be one list, or one dict. – Ned Batchelder Oct 28 '17 at 20:59
  • @NedBatchelder As I said, if the lists contain different kind of information, you probably know the amount. Therefore, it might be right to save them as variables. I use this pattern in Swift, for instance. Now, Swift isn't Python, and I understand your point in many situations, but not all. – Andreas is moving to Codidact Oct 28 '17 at 21:03
  • 2
    In another comment, the OP said the number of lists could vary. I don't want to think about what their code is ending up looking like! :) – Ned Batchelder Oct 28 '17 at 21:07
  • @AnthonyMalachiParkerIII How will you use these variables? Once you have "list13", what will you do with it? – Ned Batchelder Oct 28 '17 at 21:14

1 Answers1

-1

Well, think about it. You already have what you need:

list1 = list[0]
list2 = list[1] 
... and so on.
Hasan Jawad
  • 197
  • 9
  • Have to be able to count the number of lists in a list and assign them to separate variables. The number of lists may vary. – Tony Stark Oct 28 '17 at 20:43