Why use tuples?

Tuples typically store heterogeneous data, similar to how lists typically hold homogeneous data. It's not a hardcoded rule but simply a convention that some Python programmers follow. Because tuples are immutable, they can be used to store different data about a certain thing. For example, a contact list could conceivably be stored within a tuple; you could have a name and address (both strings) plus a phone number (integer) within a data object.

The biggest thing to remember is that standard operations, such as slicing and iteration, return new tuple objects. Commonly, lists are used for everything except when a developer doesn't want a collection to change. It cuts down on the number of collections to think about; plus, tuples don't let you add new items to them or delete data. You have to make a new tuple in those cases.

There are a few times when you simply have to use a tuple because your code requires it. However, a lot of times you never know exactly what you're going to do with your code and having the flexibility of lists can be useful.

So why use tuples? Apart from sometimes being the only way to make your code work, there are few other reasons to use tuples:

  • Tuples are processed faster than lists. If you are creating a constant set of values that won't change, and you need to simply iterate through them, use a tuple.
  • The sequences within a tuple are essentially protected from modification. This way, you won't accidentally change the values, nor can someone misuse an API to modify the data. (An API is an application programming interface. It allows programmers to use a program without having to know the details of the whole program.)
  • Tuples can be used as keys for dictionaries. One possible use of this is a crude inventory system, such as the following screenshot:

Tuples as keys
  • Tuples are great when you want to return multiple values from a function. Normally, you can only return a single value from a function. If you return a tuple, however, multiple items can be placed into a single tuple object, so you aren't violating the single value rule, because it is a single tuple, yet you still get all the items that are contained in the tuple.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.124.21