My dear, loyal Fans. Welcome back to our discussions, and here is the promised continuation of the Python Data Structures blog. I will mainly stick to the same structure but decided to add more of code examples for a much deeper explanation of details. First, in the list come Tuples…so let’s start our journey…..
Tuples are another standard sequence data type. They are used to store multiple items in a single variable. A tuple is a collection that is ordered and unchangeable. The main difference between tuples and lists is that they are immutable (unchangeable), once defined you cannot delete, add or edit any values within tuples. You may ask what is then a potential need for them? Indeed, there is…. They might be useful in situations where you need to give access to someone but you do not want them to manipulate data in your collection, instead just to see the values inside. Another fact about tuples is that they allow duplicates, since they are indexed, they can have items with the same value.
Some Tuple implementation:
Once we create a tuple, we usually assign some values to it. And this is what we call “packing” a tuple: food = (“pizza”, “brownie”, “wellington”)
However, in Python, we have a possibility to extract the values back into variables. And this is called “unpacking”:
If case if the number of variables is less than the number of values, you can add “*” to the variable name and the values will be assigned to the variable as a list:
You want to store the data similar to a telephone book style? Then dictionary is what you need. Dictionaries are used to store data values in key: value pairs. Key is used to identify the item and the value holds the value of the item. It is an unordered, mutable collection that does not allow duplicates. What does unordered mean referring to dictionaries? Well…it means that the items do not have a defined order, and you just can’t refer to an item by using an index. One more important note to make is that Keys are unique within a dictionary while values may not be. The values can be of any type.
Sets are used to store multiple, distinct (unique) objects in a single variable. That is why they might help you in your need to create lists that hold unique values in a dataset. It is both an unordered and unindexed collection, but the good news they are mutable. One more key thing worth mentioning is that sets cannot have two items with the same value in other words do not allow duplicates.
Well, now that that we are done with basic Non-primitive structures, in the final part of the blogpost we will finalize with the Lists and get to know more of their types. Specifically Linear and Non-linear lists. See you soon…and thank you for your precious time! ;)