Ad

Python: List Comprehension To Access Multiple Lists

- 1 answer

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
Ad

Answer

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.

Ad
source: stackoverflow.com
Ad