0% found this document useful (0 votes)
14 views

03 Python Data Structures

Uploaded by

mohamedyaala00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

03 Python Data Structures

Uploaded by

mohamedyaala00
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Python programming

- Data Structures -
EL Moukhtar ZEMMOURI

ENSAM – Meknès

Version 1.0 – 2024

Python Data Structures


Compound types
• Sequences
o Immutable sequences
• Strings str
• Tuples tuple
• Bytes byte
o Mutable sequences

• Lists list
• Byte Arrays bytearray

• Set types
o Sets set
o Frozen sets frozenset

• Mappings
o Dictionaries dict
E. Zemmouri, ENSAM - Meknès 3

Sequences
• Represent finite ordered sets indexed by non-negative numbers
• Built-in function len() returns the number of items
• A sequence a is indexed by 0 to len(a)-1
o Item i of sequence a is accessed by a[i]

• Sequences support slicing


o a[i:j] selects items with index k, i <= k < j.
• Immutable sequences
o Objects cannot change once it is created

• Mutable sequences
o Object can be changed after creation

E. Zemmouri, ENSAM - Meknès 4


Sequences

• Common operations :
o x in s True if an item of s is equal to x, else False
o x not in s False if an item of s is equal to x, else True
o s + t the concatenation of s and t
o s * n or n * s equivalent to adding s to itself n times
o min(s) smallest item of s
o max(s) largest item of s
o sum(s)

E. Zemmouri, ENSAM - Meknès 5

Set types

• Represent unordered, finite sets of unique, immutable objects


o è Cannot be indexed
o Can be iterated over
o Built-in function len() returns the number of items

• Common uses for sets :


o membership testing,
o removing duplicates from a sequence,
o computing mathematical operations such as intersection, union, difference,
and symmetric difference.

E. Zemmouri, ENSAM - Meknès 6


Mappings

• Represent finite sets of objects indexed by arbitrary index sets


o è index may be string, numbers, …
o a[k] selects the item indexed by k from the mapping a
o Built-in function len() returns the number of items

E. Zemmouri, ENSAM - Meknès 7

Strings

E. Zemmouri, ENSAM - Meknès 8


Strings
• Strings are arrays of bytes representing Unicode characters
• A Python str can be enclosed in single or double quotes:
o 'Hello World' is the same as "Hello World".
o String literals can span multiple lines using triple-quotes: """...""" or '''...'''

• Python does not have a char data type.


o è a single character is a string with a length of 1.

E. Zemmouri, ENSAM - Meknès 9

Strings
• Declaration, indexing, slicing

>>> a = "Hello world!" >>> s = "Hello World!"


>>> b = '"Hello world!", I said' >>> s[0] = 'h'
>>> c = """ this is TypeError: 'str' object does
... a multiline block not support item assignment
... of text """

>>> a[0]
'H' >>> a[-1] >>> b[1:6]
>>> b[0] '!' 'Hello'
'"' >>> a[-len(a)] >>> a[6:]
>>> a[11] 'H' 'world!'
'!' >>> a[0] >>> a[:5]
>>> a[12] 'H' 'Hello'
IndexError: string index out >>> a[len(a)-1] >>> b[-6:]
of range '!' 'I said'

E. Zemmouri, ENSAM - Meknès 10


Strings
• Operators, interpolation, functions, and methods
>>> p = 98.1234 >>> "Hello" + "World"
>>> r = 97.4321 'HelloWorld'
>>> print("Precision = " + str(p) + "%") >>> "Hello" * 3
Precision = 98.1234% 'HelloHelloHello'
>>> s = "Precision %.2f et Recall %.2f" %(p, r) >>> 'lo' in "Hello World"
>>> s True
'Precision 98.12 et Recall 97.43’

>>> s = "Hello Python Programmers !"


>>> s.upper() >>> a = "Hello world!"
'HELLO PYTHON PROGRAMMERS !' >>> ord('A') # the Unicode of 'A'
>>> s.split(" ") 65
['Hello', 'Python', 'Programmers', '!'] >>> ord(' ‫)' ض‬
>>> s.replace("Python", "C/C++") 1590
'Hello C/C++ Programmers !' >>> chr(65)
>>> print("Precision={} Recall={}".format(p, r)) 'A'
Precision=98.1234 Recall=97.4321 >>> chr(8364)
>>> help(str) #for more methods on strings '€'
E. Zemmouri, ENSAM - Meknès 11

Quick exercise
• Use the method find to print out indices of all occurrences of a
substring sub in a string s.

E. Zemmouri, ENSAM - Meknès 12


Lists

Lists
• A list is a collection of items
o Can contain items of different types

o But usually, the items all have the same type

>>> t = [10, 2, 25, 2] >>> len(t) >>> t = list(range(10))


>>> type(t) 6 >>> s = 0
>>> t[0] >>> for e in t :
<class 'list'>
10 ... s += e
>>> print(t)
>>> t[4] ...
[10, 2, 25, 2] >>> print(s)
'Hello'
>>> t*2 >>> t[-1] 45
[10, 2, 25, 2, 10, 2, 25, 2] 1.5 >>> sum(t)
>>> t = t + ["Hello", 1.5] >>> t[-6] 45
>>> t 10
[10, 2, 25, 2, 'Hello', 1.5] >>> t[1:4]
>>> a = [[1, 2], [10, 20]] [2, 25, 2]
>>> t[4] = 100
>>> a
>>> t
[[1, 2], [10, 20]] [10, 2, 25, 2, 100, 1.5]
E. Zemmouri, ENSAM - Meknès 14
Lists
>>> a = [1, 2, 3]
• List methods / copying lists >>> b = a
>>> a[0] = 10
>>> L = [8, 1, 5, 6, 4, 10] >>> L.index(5) >>> a
>>> L.append(15) 2 [10, 2, 3]
>>> L >>> L.index(2) >>> b
[8, 1, 5, 6, 4, 10, 15] ValueError: 2 is not in list [10, 2, 3]
>>> L.insert(1, 25) >>> 2 in L >>> a == b
>>> L False True
[8, 25, 1, 5, 6, 4, 10, 15] >>> L.sort() >>> a is b
>>> L.pop() >>> L True
15 [4, 5, 6, 8, 10, 25] >>> c = a.copy()
>>> L >>> L.reverse() >>> a[1] = 20
[8, 25, 1, 5, 6, 4, 10] >>> L >>> a
>>> L.pop(2) [25, 10, 8, 6, 5, 4] [10, 20, 3]
1 >>> L.clear() >>> c
>>> L >>> L [10, 2, 3]
[8, 25, 5, 6, 4, 10] [] >>> a == c
False

E. Zemmouri, ENSAM - Meknès 15

Quick exercise
• A matrix (2d-array) can be represented in Python as a list of lists.
o Create a matrix of zeros with size (n, m)

o Create the identity matrix with size (n, n)

E. Zemmouri, ENSAM - Meknès 16


Lists

• List comprehensions

>>> a = [x**2 for x in range(1, 6)]


>>> a
[1, 4, 9, 16, 25]
>>> b = [x**2 for x in range(10) if x%2]
>>> b
[1, 9, 25, 49, 81]

>>> n = 3
>>> m = 4
>>> M = [[0 for j in range(m)] for i in range(n)]
>>> M
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

E. Zemmouri, ENSAM - Meknès 17

Exercise
• A matrix (2d-array) can be represented in Python as a list of lists.
• Define a function that returns a random matrix with size (n, m) and values
between 0.0 and 1.0
o Hint : use function of random module

• Define a function that computes the sigmoid of a matrix.


• Define a function that computes the softmax of a matrix.

E. Zemmouri, ENSAM - Meknès 18


Dictionaries

Dictionaries
• A dictionary is an unordered collection of (key, value) pairs.
o A dictionary stores data as a key:value pair >>> list(d)
['casa', 'fes', 'ifrane']
o Dictionaries are indexed by keys >>> 'fes' in d
True
>>> d = {"fes":60, "rabat":120, "ifrane":55}
>>> d >>> for k in d.keys():
... print(k, d[k])
{'rabat': 120, 'fes': 60, 'ifrane': 55}
>>> type(d) ...
casa 300
<class 'dict’>
>>> d['rabat'] fes 60
ifrane 55
120
>>> for k, v in d.items():
>>> d["casa"] = 300
... print(k, v)
>>> d
...
{'rabat': 120, 'casa': 300, 'fes': 60, 'ifrane': 55}
>>> d.pop('rabat') casa 300
fes 60
120
>>> d ifrane 55
>>> {x:x**2 for x in (2, 4, 8)}
{'casa': 300, 'fes': 60, 'ifrane': 55}
{8: 64, 2: 4, 4: 16}
E. Zemmouri, ENSAM - Meknès 20
Tuples

Tuples
>>> t = (100, 200, 'Hello', 12.5)
• A tuple is an immutable list >>> type(t)
<class 'tuple'>
>>> t
• tuples are usually used :
(100, 200, 'Hello', 12.5)
o to pass arguments into functions >>> t[0]
100
o to return values from functions >>> t[len(t)-1]
12.5
o as keys in dictionaries. >>> t[1] = 10
TypeError: 'tuple' object does not support item
assignment
>>> a, b, c, d = t # tuple unpacking
>>> c
'Hello'
>>> L = list(t)
>>> L
[100, 200, 'Hello', 12.5]
>>> pts = [(x, x*x) for x in range(5)]
>>> pts
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]
E. Zemmouri, ENSAM - Meknès 22
E. Zemmouri, ENSAM - Meknès 23

You might also like