[Tutor] Unpacking lists

Robert Nanney nanney.56 at gmail.com
Wed Jul 9 03:44:01 CEST 2014


Hello All,

I have the following code.  The idea is to have one list that contains
all of the items from the different iterable types and maintain the
order of the items.

Python 2.7.6 |Anaconda 2.0.0 (x86_64)| (default, May 27 2014, 14:58:54)

#!/usr/bin/python
#list_test2.py

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]
one_list = zip(list1, list2, list3, list4)
print "Start: {}".format(one_list)
first_round = [one_list[x][y] for x in range(len(list3)) for y in range(4)]
print "First Round: {}".format(first_round)
second_round = []
for i in first_round:
    if not isinstance(i, list):
        second_round.append(i)
    else:
        for x in range(len(i)):
            second_round.append(i[x])
print "Second round: {}".format(second_round)

While this seems to do the trick, I feel there is probably a
better/more pythonic way to accomplish the same thing.

One thing to keep in mind is that the number of items in each list
will always be the same, ie... if list1, list2, list4 have 4 items
each, there will be 4 lists in list3.

Any advice would be greatly appreciated!

-Robert


More information about the Tutor mailing list