Rethinking Python Tuples and Their Usage

One of the most popular Python books out there, for one reason or another, encourages programmers to use the input() function when calling user input. Undoubtedly, that is a big faux pas, because so many Python users understand that it is a security hazard and that raw_input() should often be used as an alternative (and the principal reasons why raw_input() replaces and is re named as input() in Python 3).

Another instance is this post on tuples and lists. While I locate the content helpful in training new Python programmers various useful means of using slicing, I differ with the assumption that tuples

  • Alongside listings are 2 of Python’s most widely used data structures
  • are largely immutable but you can find workarounds, and
  • should be employed for program information exploitation

I ‘d say dictionaries and listings are the 2 most well-known Python information structures; tuples should not even be in that team. Actually, I ‘d even contend that tuples should not be employed to falsify program information at all, as that was not what these were usually created for. If this is the situation, then why not have listings with a read only flag?

The principal reasons why tuples exist is always to get information to and from perform calls.

Calling an international API or 3rd party function and need to move in an information structure you understand can not be transformed? Assess. Calling any function where you need to pass in just one information structure (as an alternative of individual variants)? Use “*” and you are ready to go. Formerly worked with a programing language that simply let one to return one value? Tuples are that one thing (believe of it as an individual shopping bag for all of your markets).

After all, that is not a hard-and-fast rule. Certainly a tuple can be utilized in such instances, where you aren’t going to make any alterations and want somewhat better functioning if you are wanting an information structure.

There was never any demand for tuples to have techniques because these were immutable. They’d need to convert that tuple into a listing, simply to call those systems. Beginning in 2.6, tuples now have these (and only these) techniques to prevent this additional junk: count()  and index().

So yes, it is possible to use tuples as userland information structures such instances, but that is actually it. For exploitation, use lists as an alternative. I am usually all for tutorials and more intro posts out there, as said at the best. Yet, there might be some that do not constantly impart the best patterns out there. Readers should be alert and query whether there are more “Pythonic” manners of accomplishing things. In this situation, tuples must not be among the “two of the most frequently employed built in data types in Python..”

Leave a Reply

Your email address will not be published. Required fields are marked *