0

I have a list that should contain all my other lists. Currently I append every list separately but that just looks pretty ugly..

looplist = []  # initiate an empty list that contains all date from the other lists 
[...]
looplist.append(internallist1)
[...]
looplist.append(internallist10)

the internallists are all getting initialized and filled in a for loop

ubongo
  • 87
  • 5
  • 3
    you can just `+` them (EDIT: if I understand what you're trying to do correctly, i'm not sure why you have a list of lists to begin with so perhaps this isn't your solution) – Stael Dec 03 '18 at 13:13
  • I actually don't know what is wrong with the approach OP is using or why he wants to change it, or what he's expecting to get. – Stael Dec 03 '18 at 13:33

4 Answers4

2

You can simply use + to merge them.

You may check for more info.

If you want to have list of lists, check this topic.

nerdicsapo
  • 427
  • 5
  • 16
  • I want to have lists within the looplist, so the final structure should look something like [ [list1], [list2], ... , [list n] ]. – ubongo Dec 03 '18 at 13:19
1
listOne.extend(anotherList)

this could help you: https://docs.python.org/3/tutorial/datastructures.html

you can also do listOne+=anotherList and this is less expensive, as it doesn`t involve a function call like extend

  • `list+=anotherList` looks like you're using `list` as a variable name, which is obviously a bad idea. – Stael Dec 03 '18 at 13:19
  • 1
    Assuming that OP's code works but is ugly, this will _not_ work as `extend` does something different than `append` (as does `+`). – tobias_k Dec 03 '18 at 13:20
  • can you please elaborate? @tobias_k –  Dec 03 '18 at 13:23
  • It\`s a generic way, he can use this piece of code inside the loop. –  Dec 03 '18 at 13:27
1

To answer what you are asking, Just initialize looplist with your 10 lists.

looplist = [internallist1,
            internallist2,
            internallist3] #Note: internallist3,] is also valid, python allows trailing comma. Nifty!

However, your 10 lists really shouldn't be separately named lists in the first place if this is your real use case. Just use looplist[0] through looplist[9] instead from the get go.

Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
0

The zip method could work for you as you stated your output should:

look something like [ [list1], [list2], ... , [list n] ]

in your case the code would be similar to

looplist = list(zip(internallist1,[...], internallist10))
The BrownBatman
  • 2,593
  • 1
  • 13
  • 29