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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With