python 'int' object is not iterable. Please

29 Views Asked by At

Code:

liste10=[1,[2,3],[4,5,6,7]]
for i in liste10:
    for x in i:
        print(i)

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[110], line 3
      1 liste10=[1,[2,3],[4,5,6,7]]
      2 for i in liste10:
----> 3     for x in i:
      4         print(x)

TypeError: 'int' object is not iterable

I was expecting to get [1,2,3,4,5,6,7]. I have no idea why I got such a result. I would be very happy if you could help me solve this problem. s

1

There are 1 best solutions below

0
Maria K On

You can either make liste10 a list of lists as mentioned in comments, i. e. [[1], [2, 3], [4, 5, 6, 7]] so that your code works as expected, or check type of each object in liste10 and act accordingly:

liste10 = [1, [2, 3], [4, 5, 6, 7]]

for obj in liste10:
    if isinstance(obj, list):
        for x in obj:
            print(x)
    elif isinstance(obj, int):
        print(obj)
    else:
        print("Unknown type!")

Output:

1
2
3
4
5
6
7