0

I have a list say:

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

I want to unpack it into three lists such that:

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

I can do it using slicing as:

list1 = my_list[0 : 2]
list2 = my_list[2 : 5]
list3 = my_list[5 : 10]

But I want to know if there exists a more elegant way to unpack original list into these 3 sub-lists directly.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • `list1,list2,list3 = my_list[0 : 2],my_list[2 : 5],my_list[5 : 10]`? – Scott Hunter May 07 '22 at 22:55
  • 1
    What do you mean by more elegant way ? This is already a good solution. – Deepak Tripathi May 07 '22 at 23:01
  • @DeepakTripathi I wanted to ask for solution as if we have for this case x , y , *z = [1 , 2 , 3 , 4 , 5] so this will print : x = 1 , y = 2 , z = [3 , 4 , 5] Is there some way we can do to for multiple sub lists too , since i tried using multiple starred expressions like *x , *y but that doesn't work. I thought using *x , *y = [1 , 2 , 3 , 4] could have unpacked sub lists of equal size like [1 , 2] and [3 , 4] – turning_pythonic May 07 '22 at 23:10
  • There really isn't anything simpler than what you current have. – Frank Yellin May 07 '22 at 23:36
  • I've closed your question under an existing one that covers the same sort of task. To be explicit, what you want is `list1, list2, list3 = partition(my_list, [2, 5])` (using the [top answer](/a/1198876/4518341)). LMK if you have any questions though. BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea May 08 '22 at 00:12

0 Answers0