0

I found an error in the code below:

xy=[3,5,[7,9,3,4],5,6]
flat=[]
for i in xy:
    for j in i:
        flat.append(j)
        
print(flat)

result is

    TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_37548/2722898965.py in <module>
      2 flat=[]
      3 for i in xy:
----> 4     for j in i:
      5         flat.append(j)
      6 

TypeError: 'int' object is not iterable

Please help me out

quamrana
  • 37,849
  • 12
  • 53
  • 71

1 Answers1

0

Not every object support iterating. You should first check if it is.

You can do it with the following code:

from collections.abc import Iterable


xy = [3, 5, [7, 9, 3, 4], 5, 6]
flat = []
for i in xy:
    if isinstance(i, Iterable):
        for j in i:
            flat.append(j)
    else:
        flat.append(i)
        
print(flat)

[3, 5, 7, 9, 3, 4, 5, 6]