Welcome to another post on iterables. In this post we would be talking about Tuples and Sets. Each data bundle houses other data types like numbers, strings and other iterables just like list do (Remember lists?) . They do differ however in terms of their properties and how they are used. I would really advice that you read up on lists before you continue this article. We would start with Tuples.
Tuples
A tuple is another iterable that besides sounding a bit funny also has the properties of being ordered and unchangeable. They are ordered because like lists, you can give their items indices so that the second item always has an index of one, the third an index of two and so on.
# This is what a tuple looks like:
dinosaurs = ("Velociraptor", "Tyrannosaurus", "Triceratops")
print(dinosaurs[1])
#Tyranosaurus would be printed by this code.
As for being unchangeable, well, this means that they cannot be modified (unless their items are mutable, like lists since lists can be changed). Much like the primary make of the comet that wiped off the dinosaurs they remain unchanged after they are formed. For instance if you try to modify the tuple below by altering one of the items, your code shouts at you - loudly.
# This is not a good idea...
dinosaurs = ("Velociraptor", "Tyrannosaurus", "Triceratops")
dinosaurs[2] = "Spinosaurus"
print(dinosaurs[2])
It is important to note that if you are not careful, a tuple may be confused with a string and you may get unexpected results. This happens when your tuple has only an item. See below.
# This is a string:
dinosaur1 = ("Velociraptor")
print(type(dinosaur1))
#This is a tuple:
dinosaur2 = ("Velociraptor",)
print(type(dinosaur2))
#The first code gives you "string" as the result, while the second
#says its a "tuple". If you want to find out what data type you're
#dealing with, you use type('data you're checking')
When you have only one item in your tuple, remember to add a comma at the end so it would not be confused with a string. Tuples are generally associated with the humble comma (,).
Accessing Tuple Items
You may be wondering if accessing tuple items is a lot like accessing list items and you would be right in suspecting that. Just like with lists, we harness the power of indexing to obtain tuple items.
# We can get tuple items via indexing...
dinosaurs = ("Velociraptor", "Tyrannosaurus", "Triceratops")
print(f"A {dinosaurs[2]} can eat me as a snack")
Changing Tuples
No, I did not hit my head. You read that right. I know I said that tuples cannot be modified, but like a lot of things in life, there’s a short-cut method for this. If you cannot tame a dinosaur and make him a pet, I guess you can wait for evolution to turn him into a chicken - What I’m trying to say is that we can convert tuples into another data type that can be modified and modify them accordingly; in this case we can try lists.
# The tupule becomes a list and then becomes a tuple again!
dinosaursTuple = ("Velociraptor", "Tyrannosaurus", "Triceratops")
dinosaursList = list(dinosaursTuple)
dinosaursList[0] = "Shoulder pads"
dinosaursTuple = tuple(dinosaursList)
print(dinosaursTuple)
#tuple() is known as a tuple constructor. It converts lists and sets
#to tuples. Same works with list() when other data types are to
#be converted to lists as with sets...etc
#Some may argue that shoulder pads are a type of dinosaur that
#should never return...just saying.
After the modification has occurred, we can then convert the list back into a tuple by using the tuple constructor as seen in the code snippet above. We can also remove from tuples, combine tuples and add to them. All these are possible because we convert the tuples to lists and simply perform the same operations as we did lists before converting them to tuples again.
Looping the Tuples
Our last post was about loops. We learnt about for and while loops. We gave examples but those examples were on applying them to lists. Nonetheless the same principles apply here.
#Using for loops
dinosaurs = ("Velociraptor", "Tyrannosaurus", "Triceratops")
for i in dinosaurs:
print(i)
#using while loops:
dinosaurs = ("Velociraptor", "Tyrannosaurus", "Triceratops")
i = 0
while i < len(dinosaurs):
print(dinosaurs[i])
i = i + 1
Sets
A lot of what we’d talk about here would not surprise you if you did Sets in school in Mathematics courses where you heard words like union, intersection and so on. Besides awakening your trauma I plan to explain what they are in the context of Python programs.
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
print(dinosaurs)
#This is what a set looks like
Sets are a data type in python that are unordered (unlike lists and tuples), unchangeable (like tuples) and do not allow items to be repeated. If you were to repeat "Tyrannosaurus" like in the snippet below, one "Tyrannosaurus" would be completely ignored and only one printed.
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Tyrannosaurus", "Triceratops"}
print(dinosaurs)
Since sets do not allow duplicate values meaning that each value appears just once, there is really no need for indexing in order to identify unique items; each item is unique.
Accessing Set Items
Using loops, we can access items in sets. We cannot index the items since there is no order.
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
for i in dinosaurs:
print(i)
Changing Sets
As mentioned above, sets cannot be altered. You are probably feeling clever right now and believe we could do what we proposed when we talked about tuples. Moreover, like a lot of things in life, there’s a short-cut method for this. If you cannot tame a dinosaur and make him a pet, I guess you can wait for evolution to turn him into a chicken – I was wrong. Some things don’t have short-cuts and that’s okay. Existing set items cannot be modified after creation (unless they are themselves mutable, like lists) but we can add to sets and remove from sets. We'll see how to do these in the next section.
Some Methods of Sets
There are a number of methods associated with sets that make using them more convenient. The code block below shows some of these methods and how to use them.
#Adding to sets
#add
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
dinosaurs.add("Allosaurus")
print(dinosaurs)
#Remove a particular item without shouting at you (raising an error)
#if the item doesn't exist
#discard
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
dinosaurs.discard("Velociraptor")
print(dinosaurs)
#Remove a particular item and happily shout at you (raise an error)
#if the item doesn't exist
#remove
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
dinosaurs.remove("Velociraptor")
print(dinosaurs)
#Removes a random item
#pop
dinosaurs = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
dinosaurs.pop()
print(dinosaurs)
#Combines two sets
#union
dinosaurs1 = {"Velociraptor", "Tyrannosaurus", "Triceratops"}
dinosaurs2 = {"Allosaurus", "Brachiosaurus", "Spinosaurus"}
dinosaurs3 = dinosaurs1.union(dinosaurs2)
print(dinosaurs3)
#Result is the items that are in one set but not in the other
#difference
dinosaurs1 = {"Velociraptor", "Tyrannosaurus", "Allosaurus"}
dinosaurs2 = {"Allosaurus", "Brachiosaurus", "Spinosaurus"}
dinosaurs3 = dinosaurs1.difference(dinosaurs2)
print(dinosaurs3)
#Result is the item(s) that exist in both sets
#intersection
dinosaurs1 = {"Velociraptor", "Tyrannosaurus", "Allosaurus"}
dinosaurs2 = {"Allosaurus", "Brachiosaurus", "Spinosaurus"}
dinosaurs3 = dinosaurs1.intersection(dinosaurs2)
print(dinosaurs3)
#These are only some moethods of sets. Be sure to look up the others
#when you can.
That pretty much sums up tuples and sets to some degree. In the next post we'll have a look at dictionaries.