You are on page 1of 6

Python’s Native Datatypes

Introduction

Python Python
Datatypes Datatypes

Walter Cazzola Walter Cazzola

Primitive Type Primitive Type


Boolean Boolean
Numbers Primitive Datatypes in Python Numbers In python
Collections Collections
Lists
Lists, Sets, Tuples, and so on Lists every value has a datatype,
Tuples Tuples
Sets Sets but you do not need to declare it.
Dictionaries Dictionaries

Strings Walter Cazzola Strings


Bytes Bytes
How does that work?
References References
Dipartimento di Informatica e Comunicazione Based on each variable’s assignment, python figures out what
Università degli Studi di Milano type is is and keeps tracks of that internally.
e-mail: cazzola@dico.unimi.it

Slide 1 of 22 Slide 2 of 22

Python’s Native Datatypes Python’s Native Datatypes


Boolean Numbers

Python Python
Datatypes Datatypes Two kinds of numbers: integers and floats
Walter Cazzola
Python provides two constants Walter Cazzola – no class declaration to distinguish them
– True and False
– they can be distinguished by the presence/absence of the decimal
Primitive Type Primitive Type point.
Boolean Operations on Booleans Boolean
Numbers Numbers
logic operators 1 [15:26]cazzola@ulik:~/esercizi-pa>python3
Collections Collections 2 >>> type(1)
Lists and or not Lists
3 <class ’int’>
Tuples logical and, or and negation respectively Tuples
4 >>> isinstance(1, int)
Sets relational operators Sets
5 True
Dictionaries Dictionaries
== != 6 >>> 1+1
Strings equal and not equal to operators Strings 7 2
Bytes < > <= >= Bytes 8 >>> 1+1.0
9 2.0
References less than, greater than, less than or equal to and greater References 10 >>> type(2.0)
than or equal to operators 11 <class ’float’>
12 >>>
13 [15:27]cazzola@ulik:~/esercizi-pa>
Note that python allows chains of comparisons
[17:42]cazzola@ulik:~/esercizi-pa>python3
>>> x=3
– type() function provides the type of any value or variable;
>>> 1<x<=5 – isinstance() checks if a value or variable is of a given type;
True
– adding an int to an int yields another int but adding it to a float
yields a float.

Slide 3 of 22 Slide 4 of 22
Python’s Native Datatypes Python’s Native Datatypes
Operations on Numbers Lists

Python Python
Datatypes Datatypes

Walter Cazzola Walter Cazzola A python list looks very closely to an array
Coercion & Size – direct access to the members through [];
Primitive Type Primitive Type
Boolean – int() function truncates a float to an integer; Boolean
[12:29]cazzola@ulik:~/esercizi-pa>python3
Numbers Numbers
– float() function promotes an integer to a float; >>> a_list = [’1’, 1, ’a’, ’example’]
Collections Collections >>> type(a_list)
Lists – integers can be arbitrarily large; Lists <class ’list’>
Tuples Tuples >>> a_list
Sets – floats are accurate to 15 decimal places. Sets [’1’, 1, ’a’, ’example’]
Dictionaries Dictionaries >>> a_list[0]

Strings
Operators (just a few) Strings
’1’
>>> a_list[-2]
Bytes Bytes
operators ’a’
References References [12:30]cazzola@ulik:~/esercizi-pa>
+ -
sum and subtraction operators
* ** But
product and power of operators, e.g., 2 ** 5 = 32 – negative numbers give access to the members backwards, i.e.,
/ // %
a_list[-2] == a_list[4-2] == a_list[2];
floating point and integer division and remainder opera-
tors respectively – the list is not fixed in size;
– the members are not homogeneous

Slide 5 of 22 Slide 6 of 22

Python’s Native Datatypes Python’s Native Datatypes


Lists: Slicing a List Lists: Adding Items into the List

Python Python
Datatypes Datatypes [14:13]cazzola@ulik:~/esercizi-pa>python3
>>> a_list = [’a’]
Walter Cazzola Walter Cazzola >>> a_list = a_list+[2.0, 3]
>>> a_list
[’a’, 2.0, 3]
Primitive Type A slice of a list can be yield by the [:] operator and specifying Primitive Type >>> a_list.append(True)
Boolean
the position of the first item you want in the slice and of the Boolean >>> a_list
Numbers Numbers [’a’, 2.0, 3, True]
Collections
first you want to exclude Collections

>>> a_list.extend([’four’, ’ ’])


>>> a_list

Lists Lists
[13:02]cazzola@ulik:~/esercizi-pa>python3 [’a’, 2.0, 3, True, ’four’, ’ ’]

Tuples Tuples
Sets >>> a_list=[1, 2, 3, 4, 5] Sets >>> a_list.insert(0, ’ ’)
>>> a_list[1:3] >>> a_list

Dictionaries Dictionaries
[2, 3] [’ ’, ’a’, 2.0, 3, True, ’four’, ’ ’]
Strings >>> a_list[:-2] Strings
Bytes [1, 2, 3] Bytes

>>> a_list[2:] Four ways


References References
[3, 4, 5] – + operator concatenates two lists;
[13:03]cazzola@ulik:~/esercizi-pa>
– append() method appends an item to the end of the list;
Note that omitting one of the two indexes you get respectively – extend() method appends a list to the end of the list;
the first and the last item in the list. – insert() method inserts a item at the given position.
Note
>>> a_list.append([1, 2, 3, 4, 5])
>>> a_list

[’ ’, ’a’, 2.0, 3, True, ’four’, ’ ’, [1, 2, 3, 4, 5]]

Slide 7 of 22 Slide 8 of 22
Python’s Native Datatypes Python’s Native Datatypes
Lists: Introspecting on the List Lists: Removing Items from the List

Python Python
Datatypes Datatypes

Walter Cazzola You can check if an element is in the list Walter Cazzola

>>> a_list = [1, ’c’, True, 3.14, ’cazzolaw’, 3.14]


Primitive Type >>> 3.14 in a_list Primitive Type Elements can be removed by
Boolean True Boolean
Numbers Numbers
– position
Collections Count the number of occurrences Collections >>> a_list = [1, ’c’, True, 3.14, ’cazzolaw’, 3.14]
Lists Lists >>> del a_list[2]
Tuples
>>> a_list.count(3.14) Tuples >>> a_list
Sets Sets [1, ’c’, 3.14, ’cazzolaw’, 3.14]
2
Dictionaries Dictionaries

Strings Strings
Bytes
Look for a item position Bytes – value
References >>> a_list.index(3.14) References
>>> a_list.remove(3.14)
3 >>> a_list
[1, ’c’, ’cazzolaw’, 3.14]
Note that
>>> a_list.index(’walter’)
In both cases the list is compacted to fill the gap.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.index(x): x not in list

Slide 9 of 22 Slide 10 of 22

Python’s Native Datatypes Python’s Native Datatypes


Tuples Tuples (Cont’d)

Python Python
Datatypes Datatypes

Walter Cazzola Walter Cazzola


Tuples are immutable lists. Multiple Assignments
Primitive Type Primitive Type
>>> a_tuple = (1, ’c’, True, 3.14, ’cazzolaw’, 3.14) Tuple can be used for multiple assignments and to return multiple
Boolean Boolean
>>> a_tuple
Numbers
(1, ’c’, True, 3.14, ’cazzolaw’, 3.14)
Numbers
values.
Collections >>> type(a_tuple) Collections
Lists <class ’tuple’> Lists >>> a_tuple = (1, 2)
Tuples Tuples >>> (a,b) = a_tuple
Sets Sets >>> a
Dictionaries As a list Dictionaries 1
>>> b
Strings – parenthesis instead of square brackets; Strings
2
Bytes Bytes
– ordered set with direct access to the elements through the posi-
References References
tion;
Benefits
– negative indexes count backward;
– tuples are faster than lists
– slicing.
– tuples are safer than lists
On the contrary
– tuples can be used as keys for dictionaries.
– no append(), extend(), insert(), remove() and so on

Slide 11 of 22 Slide 12 of 22
Python’s Native Datatypes Python’s Native Datatypes
Sets Sets: Modifying a Set

Python Python
Datatypes Datatypes

Walter Cazzola Walter Cazzola


Adding elements to a set
Sets are unordered “bags” of unique values.
Primitive Type Primitive Type >>> a_set = set()
Boolean
>>> a_set = {1, 2} Boolean >>> a_set.add(7)
Numbers
>>> a_set Numbers >>> a_set.add(3)
Collections {1, 2} Collections >>> a_set
Lists >>> len(a_set) Lists
{3, 7}
Tuples 2 Tuples
>>> a_set.add(7)
Sets >>> b_set = set() Sets
>>> a_set
Dictionaries >>> b_set Dictionaries
{3, 7}
set() ’ ’ ’ empty s e t ’’’
Strings Strings
Bytes Bytes
– sets do not admit duplicates so to add a value twice has no effects.
References
A set can be created out of a list References

>>> a_list = [1, ’a’, 3.14, "a string"]


Union of sets
>>> a_set = set(a_list)
>>> a_set >>> b_set = {3, 5, 3.14, 1, 7}
{’a’, 1, ’a string’, 3.14} >>> a_set.update(b_set)
>>> a_set
{1, 3, 5, 7, 3.14}

Slide 13 of 22 Slide 14 of 22

Python’s Native Datatypes Python’s Native Datatypes


Sets: Modifying a Set (Cont’d) Sets: Standard Operations on Sets

Python Python
Datatypes Datatypes

Walter Cazzola Walter Cazzola


Removing elements from a set
>>> a_set = {2, 4, 5, 9, 12, 21, 30, 51, 76, 127, 195}
Primitive Type Primitive Type
>>> a_set = {1, 2, 3, 5, 7, 11, 13, 17, 23} >>> 30 in a_set
Boolean
>>> a_set.remove(1) Boolean
True
Numbers
>>> a_set Numbers
>>> b_set = {1, 2, 3, 5, 6, 8, 9, 12, 15, 17, 18, 21}
Collections {2, 3, 5, 7, 11, 13, 17, 23} Collections >>> a_set.union(b_set)
Lists >>> a_set.remove(4) Lists {1, 2, 195, 4, 5, 6, 8, 12, 76, 15, 17, 18, 3, 21, 30, 51, 9, 127}
Tuples Traceback (most recent call last): Tuples >>> a_set.intersection(b_set)
Sets File "<stdin>", line 1, in <module> Sets {9, 2, 12, 5, 21}
Dictionaries KeyError: 4 Dictionaries >>> a_set.difference(b_set)
>>> a_set.discard(4) {195, 4, 76, 51, 30, 127}
Strings
Bytes
>>> a_set Strings
Bytes
>>> a_set.symmetric_difference(b_set) ( [ )n( \ )
’’’ A B A B ’’’
{2, 3, 5, 7, 11, 13, 17, 23} {1, 3, 4, 6, 8, 76, 15, 17, 18, 195, 127, 30, 51}
References >>> a_set.discard(17) References >>>
>>> a_set >>> a_set = {1, 2, 3}
{2, 3, 5, 7, 11, 13, 23} >>> b_set = {1, 2, 3, 4}
>>> a_set.issubset(b_set)
True
– to discard a value that is not in the set has no effects; >>> b_set.issuperset(a_set)
True
– to remove a value that is not in the set raises a KeyError exception.

Slide 15 of 22 Slide 16 of 22
Python’s Native Datatypes Python’s Native Datatypes
Dictionaries Strings

Python
Datatypes
A dictionary is an unordered set of key-value pairs Python
Datatypes

Walter Cazzola
– when you add a key to the dictionary you must also add a value for Walter Cazzola
that key Python’s strings are a sequence of unicode characters.
Primitive Type – a value for a key can be changed at any time. Primitive Type
>>> s = ’The Russian for «Hello World» is «Привет мир»’
Boolean Boolean
>>> s
Numbers Numbers
>>> SUFFIXES = {1000: [’KB’, ’MB’, ’GB’, ’TB’, ’PB’, ’EB’, ’ZB’, ’YB’], ’The Russian for «Hello World» is «Привет мир»’
Collections ... 1024: [’KiB’, ’MiB’, ’GiB’, ’TiB’, ’PiB’, ’EiB’, ’ZiB’, ’YiB’]} Collections >>> s[34]
Lists >>> type(SUFFIXES) Lists ’П’
Tuples <class ’dict’> Tuples >>> s+’!!!’
Sets >>> SUFFIXES[1024] Sets ’The Russian for «Hello World» is «Привет мир»!!!’
Dictionaries [’KiB’, ’MiB’, ’GiB’, ’TiB’, ’PiB’, ’EiB’, ’ZiB’, ’YiB’] Dictionaries >>> s[34:44]
>>> SUFFIXES ’Привет мир’
Strings Strings
{1000: [’KB’, ’MB’, ’GB’, ’TB’, ’PB’, ’EB’, ’ZB’, ’YB’],
Bytes Bytes
1024: [’KiB’, ’MiB’, ’GiB’, ’TiB’, ’PiB’, ’EiB’, ’ZiB’, ’YiB’]}
References >>> SUFFIXES[1000] = [’kilo’, ’mega’, ’giga’, ’tera’, ’peta’, ’exa’, ’zetta’, ’yotta’] References
Strings behave as lists: you can:
>>> SUFFIXES – get the string length with the len function;
{1000: [’kilo’, ’mega’, ’giga’, ’tera’, ’peta’, ’exa’, ’zetta’, ’yotta’],
1024: [’KiB’, ’MiB’, ’GiB’, ’TiB’, ’PiB’, ’EiB’, ’ZiB’, ’YiB’]} – concatenate strings with the + operator;
– slicing works as well.
The syntax is similar to sets, but
– you list comma separate couples of key/value; Note that ", ’ and ’’’ (three-in-a-row quotes) can be used to
define a string constant.
– {} is the empty dictionary
Note that you cannot have more than one entry with the same
key.
Slide 17 of 22 Slide 18 of 22

Python’s Native Datatypes Python’s Native Datatypes


Formatting Strings String Utilities

Python Python
Datatypes Datatypes Split multi-line strings on the carriage return symbol.
Walter Cazzola Python 3 supports formatting values into strings. Walter Cazzola
>>> s = ’’’To be, or not to be: that is the question:
– that is, to insert a value into a string with a placeholder. ... Whether ’tis nobler in the mind to suffer
Primitive Type Primitive Type ... The slings and arrows of outrageous fortune,
Boolean Boolean ... Or to take arms against a sea of troubles,
Numbers
Looking back at the humanise.py example. Numbers ... And by opposing end them?’’’
>>> s.split(’\n’)
Collections Collections [’To be, or not to be: that is the question:’, "Whether ’tis nobler in the mind to suffer",
for suffix in SUFFIXES[multiple]:
Lists Lists ’The slings and arrows of outrageous fortune,’, ’Or to take arms against a sea of troubles,’,
size /= multiple
Tuples Tuples ’And by opposing end them?’]
if size < multiple:
Sets Sets
return ’{0:.1f} {1}’.format(size, suffix)
Dictionaries Dictionaries

Strings Strings To lowercase a sentence.


Bytes – {0}, {1}, . . . are placeholders that are replaced by the arguments of Bytes

format(); >>> print(s.lower())


References References
to be, or not to be: that is the question:
– :.1f is a format specifier, it can be used to add space-padding, align whether ’tis nobler in the mind to suffer
the slings and arrows of outrageous fortune,
strings, control decimal precision and convert number to hexadeci- or to take arms against a sea of troubles,
mal as in C. and by opposing end them?

>>> ’1000{0[0]} = 1{0[1]}’.format(humanize.SUFFIXES[1000])


’1000KB = 1MB
To count the occurrences of a string into another.
>>> print(s.lower().count(’f’))
5

Slide 19 of 22 Slide 20 of 22
Python’s Native Datatypes References
Bytes

Python An immutable sequence of numbers (0-255) is a bytes object. Python


Datatypes Datatypes

Walter Cazzola The byte literal syntax (b’’) is used to define a bytes object. Walter Cazzola
– each byte within the byte literal can an ascii character or an encoded
hexadecimal number from \x00 to \xff.
Primitive Type
Boolean
Primitive Type
Boolean
I Jennifer Campbell, Paul Gries, Jason Montojo, and Greg Wilson.
Numbers >>> by = b’abcd\x65’ Numbers
Practical Programming: An Introduction to Computer Science Using
>>> by += b’\xff’
Collections
>>> by
Collections Python.
Lists Lists
Tuples
b’abcde\xff’
Tuples The Pragmatic Bookshelf, second edition, 2009.
>>> len(by)
I
Sets Sets
6
Dictionaries
>>> by[5]
Dictionaries Mark Lutz.
Strings 255 Strings Learning Python.
Bytes >>> by[0]=102 Bytes
Traceback (most recent call last): O’Reilly, third edition, November 2007.
References References
File "<stdin>", line 1, in <module>
TypeError: ’bytes’ object does not support item assignment I Mark Pilgrim.
bytearray(b’fbcde\xff’)
Dive into Python 3.
Bytes objects are immutable! Byte arrays can be changed. Apress*, 2009.

>>> b_arr = bytearray(by)


>>> b_arr
bytearray(b’abcde\xff’)
>>> b_arr[0]=102
>>> b_arr
bytearray(b’fbcde\xff’)

Slide 21 of 22 Slide 22 of 22

You might also like