Python tuples
are immutable lists and sets
can only contain unique values.
part of #100DaysofCode Python Edition follow along at https://jcutrer.com/100daysofcode
Python Docs Reference: https://docs.python.org/3/tutorial/datastructures.html
A tuple consists of a number of values separated by commas, for instance:
t = 2015,2016,2017,2018,2019,2020
t
tuples can be nested like lists
t2 = ((1,2,3),(4,5,6),(7,8,9))
t2
tuples are immutable
t2[0] = 101
A TypeError
exception is raised when you try to reassign a value in a tuple.
Tuples can contain other mutable data structures like lists
t3 = (["John", "Mary", "Jack"], ["Paul", "Martha", "Sam"])
t3
t3[0][2] = "David"
t3
But if we try to replace the entire list we get an error.
t3[0] = ['Susan', 'Casey', 'Lee']
Tuples can easily be convert into lists
t = ("On", "Off", "Bypass")
l = list(t)
print(l)
Lists can be converted to tuples as well
mylist = ["Running", "Walking", "Jumping"]
mytuple = tuple(mylist)
print(mytuple)
Slicing tuples work the same way as list slicing.
colors = ("red", "green", "blue", "yellow", "purple")
colors[:3]
The parentheses surrounding tuples is optional so you will sometimes see tuples define with out them.
directions = "north", "east", "south", "west"
directions
You cannot define a tuple with a single value, the expression is evaluated to the type of the solitary value.
type(("a string")) # single item tuple
type((100)) # single item tuple
type((1.333)) # single item tuple
If a single iterable is passed into tuple(). That iterables items become the items of a tuple.
In this example we are simple converting a list to a tuple.
a = tuple(['a','b','c'])
print(a)
Here is another example using range()
which is also iterable
print(tuple(range(1,10)))
namedtuple
is closely related to a tuple but allows access to data by name. This functionality comes from the collections
module which is part of the standard library.
from collections import namedtuple
Position = namedtuple('Position', ['lat', 'long'])
location = Position(34.34314, 114.38423)
print(location)
print(location.lat)
print(location.long)
Values in tuples can be unpacked into seperate variables with the use of slicing.
coords = (39.13423, -110.33234)
(lat, long) = coords
print(lat)
print(long)
Using this approach assumes that you line up the exact number of variables as items in the tuple.
coords = (39.13423, -110.33234)
(lat, long, elevation) = coords
In the above example, a ValueError
exception is raise because there is no 3rd item in the tuple.
A set is an unordered collection with mo duplicate elements.
sets are constructed using {}
curly brackets or the set()
method.
vehicles = {'car', 'truck', 'bus', 'motorcycle', 'bicycle'}
type(vehicles)
Passing a string to set()
will result in a set of all the unique letters present in the string.
set('hello how are you doing today?')
This can be very useful if you first split a larger block of text into words.
The following example will give you a set
of all the unique words.
paragraph = """Hello, how are you doing today?
I hope you have a wonderful day.
Today is actually my birthday!"""
set(paragraph.split())
Let's improve on the above code by first removing all punctuations.
paragraph = """Hello, how are you doing today?
I hope you have a wonderful day.
Today is actually my birthday!"""
punctuations = ",.!?;"
for p in punctuations:
paragraph = paragraph.replace(p, "")
set(paragraph.split())
Test if a value is present in a set
.
'bicycle' in vehicles
two or more sets can be compared using these powerful math operations to find the differenes and similarities.
Each set()
operation has both a named method and an operator.
Operation | Equivalent |
---|---|
s.issubset(t) | s <= t |
s.issuperset(t) | s >= t |
s.union(t) | s | t |
s.intersection(t) | s & t |
s.difference(t) | s - t |
s.symmetric_difference(t) | s ^ t |
compares two set
# is 123 a subset of 123456?
{1,2,3} <= {1,2,3,4,5,6}
compare two sets
# is 123 a superset of 123456?
{1,2,3} >= {1,2,3,4,5,6}
# is 123456 a superset of 123?
{1,2,3,4,5,6} >= {1,2,3}
combines two sets
{1,2,3,4,5} | {4,5,6,7,8}
{1,2,3,6} | {2,3,4,5}
Returns a set of values that are in both sets
{1,2,3,4,5,6} & {4,5,6,7,8,9}
If there is no overlap, an empty set is returned
{1,2,3,4} & {7,8,9}
returns values that are present in left set that are NOT present in right
{1,2,3,4,5,6,7,8} - {1,2,3}
{1,2,3} - {2,3,4,5,6,7,8}
returns values unique to each set
{1,2,3,4,5,6} ^ {4,5,6,7,8,9}
symetric_difference is the opposite of intersection
.add() to append items to a set
s = {1,2,3}
print(type(s))
s.add(44)
s.add('some string')
print(s)
The methods .remove()
and discard()
both remove items from a list.
s = {1,2,3,4,5,6,7,8,9,10}
s.remove(1)
s.discard(5)
s
Attempting to remove() an non-existant item from a set raises a KeyError
exception.
s.remove(100)
discard()
silently continues when you try to remove the same item.
s.discard(100)
.clear()
removes all items from a set
s = {1,2,3,4,5,6,7,8,9,10}
s.clear()
s
.pop()
removes and returns the first item in a set
s = {1,2,3,4,5,6,7,8,9,10}
item = s.pop()
print(item)
print(s)
convert a set to a comma seperated string.
weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}
','.join(weekdays)
If we attempt to do the same on a set that contains non-string values we run into a problem...
s = {1,2,3,4,5,6,7,8,9,10}
','.join(s)
A TypeError
is raised be cause the items are integers not strings.
We can fix this technically using the following comprehension which sends each item through the str()
method before joining.
s = {1,2,3,4,5,6,7,8,9,10}
','.join(str(i) for i in s)
Thanks for following along, we have come to the end of the Tuples and Sets section. Next, we will look a dictionaries.
This notebook is part of my #100DaysofCode Python Edition project.