tup=(5,2)
s=tuple(len(tup))
here I am facing a problem, please tell me why second statement is wrong in python
tup=(5,2)
s=tuple(len(tup))
here I am facing a problem, please tell me why second statement is wrong in python
Your initial variable tup
is already a tuple
. Now, let's unpack the second line step by step:
tup
, which is replaced by a reference to (5,2)
.len(tup)
---> len((5,2))
returns the number of elements in your tup
tuple, which in this case is 2.tuple
constructor. Based on the steps above tuple(len(tup))
---> tuple(len((5,2)))
---> tuple(2)
.However, if we take a look at the official documentation, we see that the tuple
constructor takes an iterable as its argument. Here's the definition of an iterable in Python:
An object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict, file objects, and objects of any classes you define with an iter() method or with a getitem() method that implements Sequence semantics.
When you try to run the second line of code, you will likely see an error that looks like this:
TypeError: 'int' object is not iterable
What this is telling you is that len(tup)
== 2 is not an iterable - it is an integer (int for short). Since integers are not iterables in python, it does not satisfy the function contract for the tuple
constructor, and your code fails.