user3373861
user3373861

Reputation: 13

Python: List Comprehension to access multiple lists

list1 = []
list.append([item1[i], item2[i], item3[i] for i in range(2)])

i.e how to populate list1 with [[item1[0], item2[0], item3[0]],[item1[1], item2[1], item3[1]]] through list comprehension where item1, item2 item3 are different lists? Example:

item1 = [1,2,3,4]
item2 = [1,4,9,16]
item3 = [1,8,27,64]

# I want list1 =
[[1,1,1],
[2,4,8],
[3,9,27],
[4,16,64]]
# through list comprehension AND APPEND STATEMENT

Upvotes: 0

Views: 521

Answers (3)

lyxal
lyxal

Reputation: 1118

Add another set of []'s to your code:

list1 = []
list1.append([[item1[i], item2[i], item3[i]] for i in range(len(item1))])

Note that this assumes that item1, item2 and item3 are all the same length

Alternately, for an exact match of your expected output, use the following:

list1 = [[item1[i], item2[i], item3[i]] for i in range(len(item1))]

Example data and output

item1 = [1, 2, 3]
item2 = ["A", "B", "C"]
item3 = [0.1, 0.2, 0.3]
list1 = [[item1[i], item2[i], item3[i]] for i in range(len(item1))]
print(list1)

>>> [[1, 'A', 0.1], [2, 'B', 0.2], [3, 'C', 0.3]]

Using .append(), the list comprehension becomes:

for i in range(len(item1)):
    list1.append([item1[i], item2[i], item3[i]])

However, if you want to use a list comprehension and still append the newly created lists onto list1, use += rather than .append():

list1 += [[item1[i], item2[i], item3[i]] for i in range(len(item1))]

.append() adds the given item onto the end of the list. += will instead add each sublist individually.

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71570

If on python 2 just do zip without list:

zip(item1, item2, item3)

Demo:

item1 = [1, 2, 3]
item2 = [4,5,6]
item3 = [7,8,9]
print(zip(item1, item2, item3))

Output:

[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

Try this:

list1 = list(zip(item1, item2, item3))

this will work until the minimum length of item1, item2, item3. If you want to go longer use itertools.zip_longest instead of zip.

example with zip:

item1 = [0,1]
item3 = [2,3]
item2 = [4,5,6]
list1 = list(zip(item1, item2, item3))

[(0, 4, 2), (1, 5, 3)]

example with itertools.zip_longest:

from itertools import zip_longest

item1 = [0,1]
item3 = [2,3]
item2 = [4,5,6]
list1 = list(zip_longest(item1, item2, item3))

[(0, 4, 2), (1, 5, 3), (None, 6, None)]

Upvotes: 4

Related Questions