-3

I have the following list:

order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]

I want to split this list into seperate lists so that it will look like this

order1 = ['S', ['PINEAPPLE']]

order2 = ['M', ['PINEAPPLE']]

order3 = ['L', ['PINEAPPLE']]

I would also like to know if its possible to make "order 1-3" into tuples instead of lists

I tried:

orders = order_str.split(",")

but that only works for strings

Rahul K P
  • 15,740
  • 4
  • 35
  • 52
Gurshaan
  • 27
  • 3
  • 2
    Does this answer your question? [How do I create variable variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) – Chris Oct 27 '22 at 05:37

2 Answers2

1

You can just unpack to those variable names from the list.

order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]
order1, order2, order3 = order

print(order2)

output

['M', ['PINEAPPLE']]

To return as tuples use;

order1, order2, order3 = map(tuple, order)
bn_ln
  • 1,648
  • 1
  • 6
  • 13
  • thank you, the only problem that I'll have with this is that the number of lists inside "order" can change and thus the number of new lists I need will change. For example I might need to create more lists called order and order 5. – Gurshaan Oct 27 '22 at 05:54
  • This is exactly the kind of situation collections like `list` and `dict` are made for. – Chris Oct 27 '22 at 06:10
  • 1
    In the [`collections` module](https://docs.python.org/3/library/collections.html), there's also `deque` which is good for building *first in first out* queues. You can append to the end and pop off the front as required, and the left pop is much more efficient in a `deque` than a `list`. – bn_ln Oct 27 '22 at 06:15
0

You can try looping through the list and naming a variable ordern; n being a number.

order = [['S', ['PINEAPPLE']], ['M', ['PINEAPPLE']], ['L', ['PINEAPPLE']]]
for i in range(len(order)):
    locals()['order'+str(i+1)] = order[i]
print(order1)
print(order2)
print(order3)

locals()[string] is used to convert string into a variable name so you can have as many order variables as you need.
You can then use the tuple(list) function to get a tuple from whatever list you want.
I don't understand why you want to seperate them but hope it helps