[Tutor] Unpacking lists

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Wed Jul 9 12:21:04 CEST 2014


On 09.07.2014 08:16, Alan Gauld wrote:
> On 09/07/14 06:58, Alan Gauld wrote:
>
>>> list1 = [1, 8, 15]
>>> list2 = [2, 9, 16]
>>> list3 = [[3, 4, 5, 6], [10, 11, 12, 13], [17, 18, 19, 20]]
>>> list4 = [7, 14, 21]
>> I'm thinking something like
>>
>> result = []
>> for L in (list1,list2,list3):
>>      if isinstance(L,list)
>>         result += L
>>      else: result.append(L)
>>
>> mebbe...
>
> Too early in the morning...
> There needs to be another loop around that.
>
> for L in (list1,list2,list3):
>     for index in len(list1):  #???
>        if isinstance(L[index],list)
>           result += L[index]
>        else: result.append(L[index])
>
> double mebbe.
> Anyway I'm off to work... :-)
>

The working solution closest to Alan's attempt appears to be:

list1 = [1, 8, 15]
list2 = [2, 9, 16]
list3 = [[3, 4, 5, 6], [10, 11, 12, 13], [17, 18, 19, 20]]
list4 = [7, 14, 21]

final = []
for outer in zip(list1, list2, list3, list4):
     for inner in outer:
         if isinstance(inner, list):
             final.extend(inner)
         else:
             final.append(inner)
print (final)

but his general idea is right.

Best,
Wolfgang


More information about the Tutor mailing list