[ Amit Kotlovski ](mailto:amit@amitkot.com) / [ @amitkot ](http://twitter.com/amitkot)
- Numbers
- Strings
- Tuples
- Lists
- Sets
- Dictionaries
intfloatlongcomplex
intis implemented as C long (32 bits at least)longis unlimitedfloatis implemented as C double
- Binary (0b prefix)
- Octal (0o prefix)
- Decimal (no prefix)
- Hexadecimal (0x prefix)
print(12 / 5)
⇒ 2 // only whole part
print(12.0 / 5)
⇒ 2.4 // exact
print(12 / 5.0)
⇒ 2.4 // exact>>> int(12.567)
12
>>> float(12)
12.0
>>> str(12.0)
'12.0'- 'this is a string'
- "this is also a string"
- """This is a long string that may span more than one line but still stay one string"""
- 'these strings are now ' + 'concatenated together'
- converting other types to string using str()
- Holds a sequence of items
- Similar to
listbut immutable
>>> t1 = (1, 2, 3)
>>> t1
(1, 2, 3)
>>> t2 = (1,)
>>> t2
(1,)
>>> t3 = 1,
>>> t3
(1,)>>> a = [1, 2, 3]
>>> tuple(a)
(1, 2, 3)Once created, a tuple does not change:
>>> t = (1, 2, 3)
>>> t
(1, 2, 3)
>>> t.add(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'add'Keeping a mutable object inside a tuple allows mutations of that object
>>> a = [1, 2, 3]
>>> t = ('first', a, 'last')
>>> t
('first', [1, 2, 3], 'last')
>>> t[1].append('banana')
>>> t
('first', [1, 2, 3, 'banana'], 'last')Accessing a single item
# third index
>>> t = ('Atreides', 'Ordos', 'Harkonnen')
>>> t[2]
'Harkonnen'
# last index
>>> t[-1]
'Harkonnen'Slicing a range
>>> t = ('Atreides', 'Ordos', 'Harkonnen')
>>> t[0:2]
('Atreides', 'Ordos')slice = tuple_name[start:end:step]
| Parameter | Description |
|---|---|
start |
first index of the slice |
end |
the index after the last index of the slice |
step |
the step to take between each item in the slice |
Example - Slicing a range with a step of 2
>>> t = (0, 1, 2, 3, 4, 5, 6, 7, 8)
>>> t[2:8:2]
(2, 4, 6)How will we slice backwards from the item at location 8 until the item at location 2 with a step of 2?
>>> t = (0, 1, 2, 3, 4, 5, 6, 7, 8)- Packing and Unpacking
- Swapping
- Adding
- Multiplying
- Length
Packing
>>> a = 1
>>> b = 2
>>> c = 3
>>> t = a, b, cUnpacking
>>> t = (5, 6, 7)
>>> a, b, c = t
>>> print(a, b, c)
5 6 7How would you swap values between two variables?
>>> a = 5
>>> b = 500
>>> print(a, b)
5 500
>>> temp = a
>>> a = b
>>> b = temp
>>> print(a, b)
500 5>>> a = 33
>>> b = 111
>>> print(a, b)
33 111
>>> a, b = b, a # Packing and Unpacking
>>> print(a, b)
111 33Adding tuples concatenates them
>>> t1 = ('a', 'b')
>>> t2 = (99, 256)
>>> t1 + t2
('a', 'b', 99, 256)Multiplying tuples is adding them to themselves
>>> t = ('a', 'b')
>>> 3 * t
('a', 'b', 'a', 'b', 'a', 'b')
>>> t * 3
('a', 'b', 'a', 'b', 'a', 'b')Using the len() function we previously met
>>> t1 = ('a', 'b')
>>> t2 = (99, 256)
>>> len(t1 + t2)
4>>> simpsons = ['Homer', 'Marge', 'Lisa', 'Maggie']
>>> simpsons.append("Santa's Little Helper")
>>> simpsons
['Homer', 'Marge', 'Lisa', 'Maggie', "Santa's Little Helper"]>>> simpsons
['Homer', 'Marge', 'Lisa', 'Maggie', "Santa's Little Helper"]
>>> simpsons.insert(2, 'Bart')
>>> simpsons
['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', \
"Santa's Little Helper"]>>> simpsons.insert(0, 'Abraham')
>>> simpsons
['Abraham', 'Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', \
"Santa's Little Helper"]Default index is last item:
>>> simpsons
['Abraham', 'Homer', 'Marge', 'Bart', 'Lisa', 'Maggie', \
"Santa's Little Helper"]
>>> person = simpsons.pop() # pop last item
>>> person
"Santa's Little Helper"
>>> simpsons
['Abraham', 'Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']Specifying index for pop:
>>> person = simpsons.pop(0) # pop at a specified index
>>> person
'Abraham'
>>> simpsons
['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']>>> simpsons
['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
>>> simpsons.remove('Lisa')
>>> simpsons
['Homer', 'Marge', 'Bart', 'Maggie']It removes only the first occurrence:
>>> cats = ['Snowball', 'Snowball II', 'Snowball III', \
'Coltrane', 'Snowball II']
>>> cats.remove('Snowball II')
>>> cats
['Snowball', 'Snowball III', 'Coltrane', 'Snowball II']Strings:
>>> baratheon = ['Robert', 'Stannis', 'Renly']
>>> baratheon.sort()
>>> baratheon
['Renly', 'Robert', 'Stannis']Numbers:
>>> numbers = [20, 500, 1, 17.3]
>>> numbers.sort()
>>> numbers
[1, 17.3, 20, 500]Reverse Sort:
>>> numbers = [20, 500, 1, 17.3]
>>> numbers.sort(reverse=True)
>>> numbers
[500, 20, 17.3, 1]mixed = [1, '2', [3, 4]]
Can we run mixed.sort()?
##Python 2 - _Yeah, OK_
##Python 3 - Nope
>>> numbers = [20, 500, 1, 17.3]
>>> sorted_numbers = sorted(numbers)
>>> numbers # did not change
[20, 500, 1, 17.3]
>>> sorted_numbers # sorted
[1, 17.3, 20, 500]>>> numbers = [20, 500, 1, 17.3]
>>> numbers.clear()
>>> numbers
[]>>> numbers = [20, 500, 1, 17.3, 20]
>>> numbers.count(20)
2>>> numbers = [20, 500, 1, 17.3]
>>> more_numbers = [999, 888, 777]
>>> numbers.extend(more_numbers)
>>> numbers
[20, 500, 1, 17.3, 999, 888, 777]Can also be achieved using +:
>>> numbers = [20, 500, 1, 17.3]
>>> more_numbers = [999, 888, 777]
>>> numbers + more_numbers
[20, 500, 1, 17.3, 999, 888, 777]>>> numbers = [20, 500, 1, 17.3, 6, 17.3]
>>> numbers.index(17.3)
3>>> numbers = [20, 500, 1, 17.3]
>>> numbers.reverse()
>>> numbers
[17.3, 1, 500, 20]>>> s = {'once', 'once', (1, 2), 5.17}
>>> s
{(1, 2), 'once', 5.17}>>> l = ['once', 'once', (1, 2), 5.17]
>>> l
['once', 'once', (1, 2), 5.17]
>>> s = set(l)
>>> s
{'once', (1, 2), 5.17}>>> s
{'once', (1, 2), 5.17}
>>> s.add('banana')
>>> s
{'once', (1, 2), 5.17, 'banana'}>>> s
{'once', (1, 2), 5.17, 'banana'}
>>> s.remove('banana')
>>> s
{'once', (1, 2), 5.17}>>> l = ['first', 'second', 'second', 'second', 'third']
>>> set(l)
{'second', 'first', 'third'}>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> yellow = {'mustard', 'lemon', 'banana', 'mango'}
>>> sweet.intersection(yellow)
{'mango', 'banana'}
>>> sweet & yellow # short syntax
{'mango', 'banana'}>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> yellow = {'mustard', 'lemon', 'banana', 'mango'}
>>> sweet.union(yellow)
{'mustard', 'banana', 'jam', 'sugar', 'lemon', 'mango'}
>>> sweet | yellow # short syntax
{'mustard', 'banana', 'jam', 'sugar', 'lemon', 'mango'}>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> yellow = {'mustard', 'lemon', 'banana', 'mango'}
>>> sweet.difference(yellow)
{'sugar', 'jam'}
>>> sweet - yellow # short syntax
{'sugar', 'jam'}>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> yellow = {'mustard', 'lemon', 'banana', 'mango'}
>>> sweet.symmetric_difference(yellow)
{'jam', 'sugar', 'mustard', 'lemon'}
>>> sweet ^ yellow # short syntax
{'jam', 'sugar', 'mustard', 'lemon'}>>> yellow_fruits = {'banana', 'mango'} # A
>>> yellow = {'mustard', 'lemon', 'banana', 'mango'} # B
>>> yellow_fruits.issubset(yellow)
True
>>> yellow_fruits < yellow # short syntax
True
>>> yellow.issuperset(yellow_fruits)
True
>>> yellow > yellow_fruits # short syntax
True>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> cars = {'Toyota', 'Mazda', 'Ford'}
>>> sweet.isdisjoint(cars)
TrueCopies the Set to a new separate one
>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> tastes = sweet.copy()
>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> has_taste = sweet.copy()
>>> has_taste.add('lemon') # add to _new_ Set
>>> has_taste
{'mango', 'banana', 'sugar', 'jam', 'lemon'}
>>> sweet # did not change
{'jam', 'mango', 'sugar', 'banana'}Removes an item from the Set, if it's there. Does not report error if not there.
>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> sweet.discard('sugar') # removes 'sugar'
>>> sweet.discard('watermelon') # item not in Set, ignores the error
>>> sweet
{'jam', 'mango', 'banana'}Extracts some item from the Set
>>> sweet = {'sugar', 'banana', 'mango', 'jam'}
>>> sweet.pop()
'mango'Remove all items from the Set
>>> sweet = {'jam', 'sugar', 'banana', 'mango'}
>>> sweet.clear()
>>> sweet
set()>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> d
{'Bill': 'blue', 'David': 'brown', 'Ron': 'black'}Equivalent to:
>>> e = dict()
>>> e['David'] = 'brown'
>>> e['Ron'] = 'black'
>>> e['Bill'] = 'blue'
>>> e
{'Bill': 'blue', 'David': 'brown', 'Ron': 'black'}- number
- string
- tuple
- immutable types
- lists
- sets
- dictionaries
- user-created types (we'll soon meet)
What will this dictionary contain?
>>> d = {'first': 'drink', 'first': 'eat'}>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> eye['Daenerys'] = 'violet'
>>> eye
{'Bill': 'blue', 'David': 'brown', 'Daenerys': 'violet',
'Ron': 'black'}| Method | Returns |
|---|---|
| d[key] | value for key, error if does not exist |
| get(key, default_val) | value for key if exists, default_val otherwise |
>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> eye['Ron']
'black'
>>> eye.get('Ron')
'black'
>>> eye.get('Owen', 'gold') # Providing default value
'gold'>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> del eye['David']
>>> eye
{'Bill': 'blue', 'Ron': 'black'}Extract an item, return it and remove it from the Dictionary:
>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> bill_eye = eye.pop('Bill')
>>> bill_eye
'blue'
>>> eye
{'David': 'brown', 'Ron': 'black'}Providing a default value, in case the key does not exist:
>>> eye.pop('George', 'green')
'green'
>>> eye
{'David': 'brown', 'Ron': 'black'}Pop some item from the Dictionary:
>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> eye.popitem()
('Bill', 'blue')>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> 'Ron' in eye
True
>>> 'Jon' not in eye
True>>> eye
{'Bill': 'blue', 'David': 'brown', 'Ron': 'black'}
>>> eye.clear()
>>> eye
{}>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> eye_same = eye
>>> eye_backup = eye.copy()
>>> eye['David'] = 'RED'
>>> eye
{'Bill': 'blue', 'David': 'RED', 'Ron': 'black'}
>>> eye_same
{'Bill': 'blue', 'David': 'RED', 'Ron': 'black'}
>>> eye_backup
{'Bill': 'blue', 'David': 'brown', 'Ron': 'black'}A direct connection to the actual keys, values and items:
>>> eye = {'David': 'brown', 'Ron': 'black', 'Bill': 'blue'}
>>> k = eye.keys()
>>> v = eye.values()
>>> i = eye.items()Changes to the dictionary affect them:
>>> eye['Sarah'] = 'green'
>>> k
dict_keys(['Bill', 'David', 'Sarah', 'Ron'])
>>> v
dict_values(['blue', 'brown', 'green', 'black'])
>>> i
dict_items([('Bill', 'blue'), ('David', 'brown'),
('Sarah', 'green'), ('Ron', 'black')])- Tuples are immutable lists
- Lists are ordered data collections with sort, find and more
- Sets are collections with no duplicate items
- Dictionaries map keys to values
All Rights Reserved to Amit Kotlovski
