0

I try to make flat list. Now I have list:

L=['aa',['bb','cc']]

and I try:

L=['aa',['bb','cc']]
new=[]

for i in L:
  print i
  new+=i

print new

and I got:

'aa'

['bb','cc']

['a','a','bb','cc']

Why in print i=0 = 'aa' and in new+=i i=0 is only 'a'?

How i could get list ['aa','bb','cc']?

Kos
  • 70,399
  • 25
  • 169
  • 233
Lookasz_BL
  • 43
  • 4
  • You need to avoid iterating over strings; see my answer [here](http://stackoverflow.com/a/23407650/3001761), which works recursively and special-cases strings. – jonrsharpe Aug 20 '14 at 08:42
  • the problem is your += which expects iterable on either side of the equation and extends the left with the right, right in your case is 'aa' which is being treated as two elements iterable like ['a', 'a'] – user3012759 Aug 20 '14 at 09:01

3 Answers3

1

In general, meaning when you don't know the depth of the original list, this should work:

L=['aa',['bb','cc', ['dd', 'ee']], 'ff']
new = []
for l_item in L:
    stack = [ l_item ]
    while stack:
        s_item = stack.pop(0)
        if isinstance(s_item, list):
            stack += [ x for x in s_item ]
        else:
            new.append(s_item)
print new 

This gives:

['aa', 'bb', 'cc', 'dd', 'ee', 'ff']
perreal
  • 94,503
  • 21
  • 155
  • 181
1

Well, don't forget that strings are iterable in Python.

>>> new = []
>>> new += 'aa'
>>> print new
['a', 'a']

To be sure of adding what you want, you can proceed this way:

>>> L = ['aa',['bb','cc']]
>>> new = []

>>> for e in L:
...     new.extend(e if type(e) == list else (e,))
>>> print new
['aa', 'bb', 'cc']

Seriously,


P.S. You can look at this post ... for more information.

Community
  • 1
  • 1
Taha
  • 709
  • 5
  • 10
0

This happens because you iterate over 'aa', basically treating it like it was ['a', 'a'].

If you want to avoid iterating over strings, you can look at the type:

for i in L:
    if isinstance(i, list):
        new += i
    else:
        new.append(i)

See this question for more details and how to do it recursively:

Flatten (an irregular) list of lists

Community
  • 1
  • 1
Kos
  • 70,399
  • 25
  • 169
  • 233