We've just learned about different data types and containers. Now, let's try to actually do something with them. To review, the different data types and containers we've seen are:
Now, let's explore what happens when we use the plus sign to "add" different data types
#Floats:
1.0 + 3.0
4.0
#Integer
1 + 3
4
A float returns a float and an integer returns an integer, what do you think a 1.0 + 3 returns?
#Float + Integer
1.0 + 3
4.0
What about adding strings?
'a' + 'b'
'ab'
Adding strings concatonates the two strings
Let's try adding Booleans
True + False
1
True + True
2
False + False
0
Here True and False behave as the integers 1 and 0 respectively
Now that we've gone through our data types, let's review:
* Integer: + adds mathematically to produce an integer
* Float: + adds mathematically to produce a float
* String: + concatonates the 2 strings to produce a string
* Boolean: + adds mathematically assigning True = 1 and False = 0
Given the behavior we saw above, can you predict what will happen if we add 2 Tuples?
#Tuples
a = (1, 2, 3, 4)
b = ('a', 'b', 'c')
a+b
(1, 2, 3, 4, 'a', 'b', 'c')
Tuples concatonate just like strings. How do you think Lists will behave?
#Lists
a = [1, 2, 3, 4]
b = [5, 6, 7, 8]
a+b
[1, 2, 3, 4, 5, 6, 7, 8]
Notice that lists don't add element wise as you may have expected. Like Tuples, they concatonate.
So far everything we have tried has had some possible "addition" behavior. Do you think that dictionaries can be "added"? Why or Why not?
#Dictionaries
a = {'one': 1, 'two': 2, 'three': 3}
b = {'four': 4, 'five': 5}
a+b
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-14-7a771ae2092f> in <module>() 1 a = {'one': 1, 'two': 2, 'three': 3} 2 b = {'four': 4, 'five': 5} ----> 3 a+b TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
What about sets?
#Sets
a = set([1, 2, 3, 4])
b = set([4, 5, 6, 7])
a+b
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-17-b22d2ad9a826> in <module>() 2 a = set([1, 2, 3, 4]) 3 b = set([4, 5, 6, 7]) ----> 4 a+b TypeError: unsupported operand type(s) for +: 'set' and 'set'
Why don't sets and dictionaries work? Hint: What makes a set different from a list?
Dictionaries and sets require unique keys and elements (respectively). There is no easy way to define adding them in a way that works for all dictionaries or all sets (concatenation: What if your dictionaries a and b have the same key?, mathematical addition: What if your sets are different lengths?)
* Tuple: concatonates and returns a tuple
* Lists: concatonates and returns a list
* Dictionary: cannot "add" because container requires unique elements
* Set: cannot "add" because container requires unique elements