user5030291
user5030291

Reputation: 1

How to get values from lists of lists and add them to smaller lists

Say I have some lists like so:

myList1 = [1,2,3]
myList2 = [7,8,9]
myList3 = [13,14,15]

And I append them to a larger list:

myBigList = []
myBigList.append(myList1)
myBigList.append(myList2)
myBigList.append(myList3)

And now I have smaller lists like such:

a = []
b = []
c = []

How would I iterate through my 'myBigList' list, and pull out the first value of all the smaller lists and store those values in A, the second values of all my shorter lists, in B, and the shorter of all the third in c? I appreciate all the help.

Upvotes: 0

Views: 60

Answers (2)

Iron Fist
Iron Fist

Reputation: 10951

a = [x[0] for x in myBigList]
b = [x[1] for x in myBigList]
c = [x[2] for x in myBigList]

EDIT: more efficient and optimized solution

a,b,c = [[x[i] for x in myBigList] for i in range(3)]

Upvotes: 2

TigerhawkT3
TigerhawkT3

Reputation: 49310

zip is great.

>>> myList1 = [1,2,3]
>>> myList2 = [7,8,9]
>>> myList3 = [13,14,15]
>>> myBigList = []
>>> myBigList.append(myList1)
>>> myBigList.append(myList2)
>>> myBigList.append(myList3)
>>> myBigList
[[1, 2, 3], [7, 8, 9], [13, 14, 15]]
>>> a, b, c = zip(*myBigList)
>>> a
(1, 7, 13)
>>> b
(2, 8, 14)
>>> c
(3, 9, 15)

Are you using myBigList for something? If you want, you can arrive at a, b, and c without putting them into myBigList at all.

>>> a, b, c = zip(myList1, myList2, myList3)
>>> a
(1, 7, 13)
>>> b
(2, 8, 14)
>>> c
(3, 9, 15)

Upvotes: 3

Related Questions