0
tup=(5,2)
s=tuple(len(tup))

here I am facing a problem, please tell me why second statement is wrong in python

1 Answers1

1

Your initial variable tup is already a tuple. Now, let's unpack the second line step by step:

  1. The innermost statement is evaluated first, i.e tup, which is replaced by a reference to (5,2).
  2. Next, len(tup) ---> len((5,2)) returns the number of elements in your tup tuple, which in this case is 2.
  3. You then try to create a tuple by using the 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.

v0rtex20k
  • 1,041
  • 10
  • 20