Chapter 3 PPT
Chapter 3 PPT
Python Fundamentals
Strings – advanced operations
• Used to save raw data input and messages used in an application
• Can be seen as advanced data structures due to some of their properties
• They allow using indexes and slicing
>>> S = Academy'
>>> len(S)
8 – length of a string
>>> S[0]
'A' – first element in the string
>>> S[1]
'c' – second element in the string
Using indexes in a string
>>> S[-1]
'e' – last element in the string
>>> S[-2]
'i' – second to last element in the string
>>> S[-1]
'e' - last element in the string
>>> S[len(S)-1]
'e' – equivalent way of printing the last element in the string
Slicing in a string
>>> S[1:3]
'ca' – second and third elements in a string; doesn’t include the fourth one
>>> S[1:]
'cademy' – all elements from the second one to the very last one
>>> S[0:3]
'Aca' – elements from the first position to the third one, without including the
fourth one
>>> S[:3]
'Aca' – characters from the first position to the third one, without including the
fourth one
Other string operations
>>> S[:-1]
'Academ' – from the first character to second to last one
>>> S[:] – the whole string
'Academie'
>>> S * 3
'AcademyAcademyAcademy' - *3 is concatenating the string 3 times
>>> S.upper()
'ACADEMY'
>>> S.capitalize()
'Academy'
Immutable strings
• Immutability gives an object the property of being final; it doesn’t
accept any modifications on its elements
• All the operations that were described to this point are not modifying
the existing instances – they are creating new ones
>>> S[0] = "a"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
Immutable strings
• In order to save the new string, created on the existing one, we need to use the
assignment operator
• S.upper() will not modify the string to which the S reference is pointing; it will simply
return a new string, without reference
• Pentru a atribui noul șir de caractere trebuie folosit
s = s.upper()
>>> line.rstrip(8) #argumentele metodelor de tip strip() trebuie să fie șiruri de caractere
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: rstrip arg must be None, str or Unicode
>>> line.rstrip('8')
' a,b,c‘
Lists
• The most general data sequence
• Ordered collection, non-homogeneous from a data type perspective
• Variable length, can add or remove data without worrying about max.
length
• Mutable objects
• Indexed elements
>>> L
[2.35, 'spam', 'NI']
>>> L[99] – referring to a non existent index will generate an
exception
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Parsing elements in a list
>>>my_list = [1, 2, 3]
>>> for x in list: print(x, end = ‘ ’)
1 2 3 #x will take the value from each element in the list
>>>for i in range(len(lista_mea)): print(lista_mea[i], end = ‘ ’)
1 2 3 #the result will be the same, but the parsing was done in a
different manner, based on indexes
Converting to lists
• In the same manner as basic data types, list() can be used to
convert other data types to lists
>>> t = list("test")
>>> print(t)
['t', 'e', 's', 't']
Nested lists (matrices)
• Because lists are not homogenous, amongst their elements we can have other
lists as well
>>> M = [[1,2,3],
... [4,5,6],
... [7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[1]
[4, 5, 6]
>>> M[1][2]
6
Tuples
• Sequence of data very similar to lists
• Elements from a tuple are immutable (like strings)
• Elements can be referenced by index
We can notice that some property from the lists will also be applied on tuples.
Common methods for working with tuples
>>> e = ()
>>> e
()
>>> type(e)
<class 'tuple'>
>>>
>>>
>>> 5 in (3, 5, 17, 257, 65537)
True
>>> 5 not in (3, 5, 17, 257, 65537)
False
Correctly initializing tuples with data
>>> h = (391) – after this initialization, we don’t have a tuple in h
>>> h
391
>>> type(h)
<class 'int'>
>>> k = (391,) – we need to use a comma to mark that we are
working with a tuple
>>> k
(391,)
>>> type(k)
<class 'tuple'>
Adding elements to a tuple
• As we stated before, tuples are immutable, and we can’t actually add
elements to it
• We are actually creating a new tuple, with modified data from the initial
one
>>>my_tuple = (1, 2, 3)
>>> my_tuple = (1, 2, 3) + (4) – this operation will generate an exception
since (4) is considered as an int
>>>my_tuple = (1, 2, 3) + (4, )
>>> my_tuple
(1, 2, 3, 4)
Sets
• Unordered collection of objects – we can’t refer to them using an
index anymore
• The elements in a set are unique and immutable
Sets initialization:
• my_set = {1, 2, 3}
• my_set = set()
Attention!
• my_set = {} – will initialize a dictionary, not a set
Working with sets
>>> my_set = {6, 6, 28, 496, 8128, 6, 33550336} # correctly
initializing a set
>>> my_set
{33550336, 496, 28, 6, 8128} # we can easily noticed that
duplicated elements were eliminated
>>> type(p)
<class 'set'>
Working with sets
>>> s = set([2,4,16,64,4096,65536,262144]) # converting a list to a set using set()
>>> s
{4096, 64, 2, 65536, 4, 262144, 16}
>>>
>>> q = {2, 9, 6, 4}
>>> 3 in q # verifying if 3 is in the set
False
>>> 3 not in q # verifying if 3 is NOT in the set
True
Common methods for working with sets
>>> k = {81, 108}
>>> k.add(54) # adding elements to the set; duplicate values are ignored
>>> k
{81, 108, 54}
>>> k.update([37, 128, 97]) # update function gives the possibility to add multiple
elements to the set, if they are grouped in a list
>>> k.remove(97) – removes a specific element from the set
>>> k
{128, 37, 108, 81, 54}
Common methods for working with sets
>>> k.remove(98) – an exception is thrown if the element doesn’t exist in the set
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 98
>>> k.discard(98) – discard performs the same functionality as remove, but it doesn’t
throw an exception if the element doesn’t exist in the set
Algebraic operations on sets
Supported operations are:
• union
• intersection
• difference.
>>> a = {1, 2, 3}
>>> b = {2, 3, 4, 5}
>>> a.union(b)
{1, 2, 3, 4, 5}
>>> a.intersection(b)
{2, 3}
>>> a.difference(b)
{1}
Dictionaries
• Data structures which permit saving elements in a key – value format
• Known as maps or JSONs in other programming languages.
• The keys are unique and immutable (they are actually a set)
• Values are mutable and can contain duplicates
• Order of the elements in a dictionary is arbitrary
Dictionary initialization:
• my_dict = dict()
• my_dict = {}
Working with dictionaries
Items în acest caz înseamnă elementele iterabile ale unui dicționar și la fiecare
iterație se obține un Tuplu. Folosind Tuplu unpacking obtinem valorile în key și
value pe care le printăm.
Working with dictionaries
The in and not in operators are working with the keys from a
dictionary
>>> stocks
{'IBM': 194, 'YHOO': 25, 'AAPL': 416, 'GOOG': '895'}
>>> "GOOG" in stocks
True
>>> "GOOGLE" in stocks
False
>>> "GOOGLE" not in stocks
True
Working with dictionaries
>>> del stocks['YHOO'] # deletes both the key and the value from
the dictionary
>>> stocks
{'IBM': 194, 'AAPL': 416, 'GOOG': '895'}
Exercises
1.Create a list with initial values of your own choice. Add other values to that list. Delete the values
from the 0 and 2 indexes from that list. Re-initialize the list to an empty one
2.Create 3 sets with values specified by the instructor. Apply the following operations on them:
intersect, difference, union.
3.Write a program that creates a dictionary and displays all its elements (in a key-value format) by
using a for structure, one below the other. Display an element from the list by referring to its key.
4.Read multiple input words from a single line (separated by whitespaces). Build a dictionary in the
following format: the keys are represented by words and values by the number of their repetition in
the initial input.
5.Read a value N from the user. Following that, read N numerical values from the user on separate
lines and display the percentage of the unique values, as well as all the data that was read.