Tuple


Collection Type Ordered Mutable Duplicate Elements Indexing Example
Tuple Yes No Yes Yes (2, "beam_12", 42.1234, False)


A tuple is a collection that is ordered and unchangeable. It allows duplicate members.

# To create (instantiate)
a = (2,beam_12,42.1234,True,False)

# To retrieve an element
b = a[2]  # 42.1234

# To remove an element
impossible!

# To insert an element
impossible!


🦊 Remember that tuples are different from lists and depending on the situation, they can offer advantages:

  • **Immutability**: Once a tuple is created, it cannot be changed. This is useful when you want to group together several related values and ensure that they stay constant. For example, the properties of a beam (length, width, height, and wood type) would not change once the beam is created, so it makes sense to store them in a tuple.

  • **Semantic Meaning**: Tuples are often used to group related data that belongs to a single logical entity. In this case, the length, width, height, and wood type all describe a single beam. Using a tuple makes it clear that these values belong together.

  • **Unpacking**: Tuples can be easily unpacked into individual variables. This can be useful if you want to use the individual properties of the beam in your code. For example, you could do length, width, height, wood_type = beam_1 to unpack the properties of beam_1.

  • **Hashability**: Unlike lists, tuples can be used as dictionary keys because they are immutable. This could be useful if you wanted to create a dictionary where each key is a beam (represented by a tuple), and the value is some property of the beam, like its weight.


🛠 Exercise


🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍