16

I am trying to flatten a list using list comprehension in python. My list is somewhat like

[[1, 2, 3], [4, 5, 6], 7, 8]

just for printing then individual item in this list of list I wrote this function:

def flat(listoflist):
    for item in listoflist:
        if type(item) != list:
            print(item)
        else:
            for num in item:
                print(num)

interactive output:

>>> flat(list1)
1
2
3
4
5
6
7
8

Then I used the same logic to flatten my list through list comprehension I am getting the following error

list2 = [item if type(item) != list else num for num in item for item in list1]

Which gives me the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

How can I flatten this type of list-of-list using using list comprehension ?

Neuron
  • 5,141
  • 5
  • 38
  • 59
Anurag Sharma
  • 4,839
  • 13
  • 59
  • 101

6 Answers6

28

No-one has given the usual answer:

def flat(l):
  return [y for x in l for y in x]

There are dupes of this question floating around StackOverflow.

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
  • 6
    Your code does not work for the list the OP provided because his list includes non-iterable objects, namely integers. Your code does however work if every item in the list is an iterable object. See my comment below. – JDG May 26 '15 at 12:55
  • 1
    Thanks for pointing that out - I'll actually need to find a moment to mess around with that and come to grips... – GreenAsJade May 26 '15 at 23:36
  • 1
    Double `for` is interesting. The above problem can also be solved using: `[z for y in [x if isinstance(x, list) else [x] for x in [1, [2]]] for z in y]`. – Nishant Mar 19 '22 at 10:39
13
>>> from collections import Iterable
>>> from itertools import chain

One-liner:

>>> list(chain.from_iterable(item if isinstance(item,Iterable) and
                    not isinstance(item, basestring) else [item] for item in lis))
[1, 2, 3, 4, 5, 6, 7, 8]

A readable version:

>>> def func(x):                                         #use `str` in py3.x 
...     if isinstance(x, Iterable) and not isinstance(x, basestring): 
...         return x
...     return [x]
... 
>>> list(chain.from_iterable(func(x) for x in lis))
[1, 2, 3, 4, 5, 6, 7, 8]
#works for strings as well
>>> lis = [[1, 2, 3], [4, 5, 6], 7, 8, "foobar"]
>>> list(chain.from_iterable(func(x) for x in lis))                                                                
[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']

Using nested list comprehension:(Going to be slow compared to itertools.chain):

>>> [ele for item in (func(x) for x in lis) for ele in item]
[1, 2, 3, 4, 5, 6, 7, 8, 'foobar']
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
3

You're trying to iterate through a number, which you can't do (hence the error).

If you're using python 2.7:

>>> from compiler.ast import flatten
>>> flatten(l)
[1, 2, 3, 4, 5, 6, 7, 8]

But do note that the module is now deprecated, and no longer exists in Python 3

TerryA
  • 58,805
  • 11
  • 114
  • 143
3

An alternative solution using a generator:

import collections

def flatten(iterable):
    for item in iterable:
        if isinstance(item, collections.Iterable) and not isinstance(item, str):  # `basestring` < 3.x
            yield from item  # `for subitem in item: yield item` < 3.3
        else:
            yield item

>>> list(flatten([[1, 2, 3], [4, 5, 6], 7, 8]))
[1, 2, 3, 4, 5, 6, 7, 8]
Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
2
def nnl(nl):    # non nested list

    nn = []

    for x in nl:
        if type(x) == type(5):
            nn.append(x)

    if type(x) == type([]):
        n = nnl(x)

        for y in n:
            nn.append(y)
    return nn

print (nnl([[9, 4, 5], [3, 8,[5]], 6]))  # output: [9, 4, 5, 3, 8, 5, 6]
  • Probably an explanation would be helpful as well. – scopchanov Aug 24 '18 at 14:17
  • This solution uses **recursion.** For every element in the nested list you check if the element is an integer or a list. If an integer, we append that integer in the list nn. If the element in the nested list is a list, call a recursive function, you will do to the sublist what you did to the initial nested list. Then append the elements that are not a list again in nn. The output of nn will be a non nested list. Happy coding everybody! – Alessandro Anderson Aug 25 '18 at 09:46
  • Great! Now please [edit your answer](https://stackoverflow.com/posts/52006022/edit) adding this information. – scopchanov Aug 25 '18 at 09:49
  • 1
0

Here's a more efficient and fast solution using precision and generators that will also work with highly nested lists.

Implementation

def _flatten_list(l: list):
    for item in l:
        if isinstance(item, list):
            yield from flatten_list(item)
        else:
            yield item
            
def flatten_list(l: list):
    return list(_flatten_list(l))
        
example = [1, 2, [3, 4, [5, 6], 7], 8, [9, [10]]]
print(flatten_list(example))

Output

> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Kayvan Shah
  • 375
  • 2
  • 11