Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate in a list that contain tuples and int in Python

So I have created this list :

l = [(1,2,3),(4,5),6]

But when I do this :

for i in l:
    print (i[0])

It send me this error message :

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: object of type 'int' has no len()

So I want to know if you there is a method to print the number if it's an int or the first element if it is a tuple...

I hope I made it clear for you, do not hesitate to ask if you don't understand.

Thank you in advance.

like image 826
Senseikaii Avatar asked Dec 06 '25 23:12

Senseikaii


2 Answers

Use isinstance:

l = [(1,2,3),(4,5),6]
for i in l:
    if isinstance(i,int):
        print(i)
    elif isinstance(i,tuple):
        print(i[0])
# 1
# 4
# 6

Using list comprehension, output as a form of list:

[i if isinstance(i,int) else i[0] for i in l]
# [1, 4, 6]
like image 70
meW Avatar answered Dec 08 '25 15:12

meW


To support other data types (floats instead of ints, lists instead of tuples):

for i in l:
    try:
        print(i[0])
    except TypeError:
        print(i)

Note that this won't work if you want to print all chars of a string.

like image 40
iz_ Avatar answered Dec 08 '25 16:12

iz_