Reputation: 60
I was experimenting with tuple in python and stumbled upon this problem
t=tuple("2",) # works
but
t=tuple(1,) # fails
with error TypeError: 'int' object is not iterable
whereas
t=(1,) # works
Can anybody please explain why this is so?
Upvotes: 0
Views: 863
Reputation: 61526
t=tuple(1,)
Because the parentheses here are for a function call, this is the same as t=tuple(1)
. So the exception is raised because you are requesting a tuple made out of all the elements that result from iterating over 1
, but 1
is not the appropriate sort of thing for that.
t=(1,)
Now the `(1,) indicates a tuple.
Upvotes: 0
Reputation: 68
Its because in the first and second example, you're attempting to cast it into a tuple, while the last example you're creating a tuple.
t = tuple("a") # this is casting "a" into a tuple
t = ("a") # this is creating a tuple
As to why it works for string and not int, its because string is iterable.
some_string = "a"
print(tuple(some_string)) # ('a',)
some_other_string = "asd"
print(tuple(some_other_string)) # ('a', 's', 'd')
Upvotes: 1
Reputation: 12031
The tuple()
function has a signature of tuple(iterable)
. It is not the same as creating a tuple using parentheses. In fact, the parentheses, while preferable, are optional.
The reason tuple("2")
works is because strings are iterable in Python. You can do the following in python:
for i in "2":
# ...
But you can't do the following:
for i in 1:
# This causes a "TypeError: 'int' object is not iterable" error
If you wanted the int tuple in your example you could do it in the following ways:
t = tuple([1])
t = (1,)
t = 1,
Upvotes: 0
Reputation: 2421
As the TypeError
also states, you can pass only iterables to a tuple.
A simple int
item is not iterable, so that cannot work.
(1, )
works because 1,
is already an iterable. Actually it is another tuple.
In a similar fashion, you can also adjust the failed tuple(1,)
case to tuple((1, ))
and it will also work.
Upvotes: 0
Reputation: 17368
The error message clearly explains why there's an error.
TypeError: 'int' object is not iterable
This means tuple()
is expecting an iterable.
What data structures are iterable in python? --> list, set etc...
Hence, give an iterable like list or set to the tuple
function. It will function. It's basically used for converting any iterable to tuple object.
So, the below works:
t = tuple([1,])
But in t = (1,)
you already are creating a tuple object
Upvotes: 1