Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Declaring length of tuple/list into a tuple

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading