3

I have a lists of lists:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

How would I be able to add each column of the list to an empty list. By column I mean, lst[i][column], e.g. 1,1,1 then 2,2,2, etc. and get a new list like this:

[1,1,1,2,2,2,3,3,3]

So far I have tried:

pos = 0
column = 0
row = 0
i = 0
empty = []
while i < len(lst):
    empty.append(lst[i][0])
    i += 1
print(empty)
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
ghost97
  • 75
  • 6

4 Answers4

4

Here's a functional way to achieve this via using combination of itertools.chain() and zip() as:

from itertools import chain

my_list = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

new_list = list(chain(*zip(*my_list)))

where new_list will hold:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

Refer below links to know more about these functions:

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
3

You can use itertools.chain and really work the star operator:

from itertools import chain

[*chain(*zip(*lst))]  
# or more classic:
# list(chain.from_iterable(zip(*lst)))
# [1, 1, 1, 2, 2, 2, 3, 3, 3]

or use the transpositional pattern zip(*...) shown above in a simple nested comprehension:

[x for sub in zip(*lst) for x in sub]
# [1, 1, 1, 2, 2, 2, 3, 3, 3]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • for `chain.from_iterable()` +1 lol – Red Jan 17 '21 at 14:50
  • 1
    One might note that `chain.from_iterable` is not really beneficial for most of these academic SO questions where you do consume the entire iterable anyway. Its real power is when used in a context where you might have some short-circuit logic (or the iterable is infinite) where `*` unnecessarily unpacks spurious elements or even runs out of memory. – user2390182 Jan 17 '21 at 14:54
2

Here is how you can use a nested list comprehension:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

print([v[i] for i in range(len((lst[0]))) for v in lst])

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

The nested list comprehension above is the equivalent of this nested for loop:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

arr = list()
for i in range(len((lst[0]))):
    for v in lst:
        arr.append(v[i])
print(arr)

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]

Finally, you can use the built-in zip() method:

lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]

print([j for i in zip(*lst) for j in i])
Red
  • 26,798
  • 7
  • 36
  • 58
2
lst = [
    [1,2,3],
    [1,2,3],
    [1,2,3]
]
new_list = []
for i,j in enumerate(lst):
    new = lst[i]
    new_list.extend(new)

new_list = sorted(new_list)

print(new_list)

Output:

[1, 1, 1, 2, 2, 2, 3, 3, 3]
Bruno
  • 655
  • 8
  • 18