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

Chapter 3 PPT

The document discusses advanced string operations in Python like indexing, slicing, and string methods. It also covers lists, tuples, and sets - their initialization, common operations and methods. Lists are mutable sequences that can contain heterogeneous data types. Tuples are similar to lists but immutable. Sets contain unique elements and do not maintain element order.

Uploaded by

id
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
90 views

Chapter 3 PPT

The document discusses advanced string operations in Python like indexing, slicing, and string methods. It also covers lists, tuples, and sets - their initialization, common operations and methods. Lists are mutable sequences that can contain heterogeneous data types. Tuples are similar to lists but immutable. Sets contain unique elements and do not maintain element order.

Uploaded by

id
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 41

Chapter 3

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()

>>> S = 'z' + S[1:]


>>> S
'zcademy'
Common methods for working with strings
>>> S = ‘Academy’
>>> S.find('dem')
3

>>> S.replace('demy','demy one')


'zcademy one'

>>> line = 'aaa,bbb,ccccc,dd'


>>> line.split(',')
['aaa', 'bbb', 'ccccc', 'dd']
Common methods for working with strings
>>> line='aaa,bbb,ccc'
>>> line.split() #split is implicitly splitting after the whitespace character
['aaa,bbb,ccc'] #the result will be a list with a single element, as there were no spaces in the initial line
>>> line
'aaa,bbb,ccc'
>>> line=line.split()
>>> line
['aaa,bbb,ccc']
>>> line=line.split(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'split'
>>> line[0]
'aaa,bbb,ccc'
>>> line[0].split(',')
['aaa', 'bbb', 'ccc']
>>> line=line[0].split(',')
>>> line
['aaa', 'bbb', 'ccc']
Common methods for working with strings

>>> line = 'aaa,bbb,ccccc,dd\n'


>>> line
'aaa,bbb,ccccc,dd\n'
>>> line = line.rstrip()
>>> line
'aaa,bbb,ccccc,dd'
>>> '%s, eggs, and %s' % ('spam', 'SPAM!')
'spam, eggs, and SPAM!'
>>>
Common methods for working with strings
>>> line=' a,b,c '
>>> line.rstrip()
' a,b,c‘ #we can notice that only the characters from the right side are deleted
>>> line=' a,b,c8888'
>>> line.rstrip()
' a,b,c8888‘ #no characters are deleted since no whitespaces are on the right

>>> 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

List initialization can be done either:


• my_list = []
• my_list = list()
Working with lists
>>> L = [2.35, 'spam', True] #non-homogeneous example of list
>>> len(L) #number of elements in a list
3
>>> L[0] # first item in the list; same indexing as string
2.35
>>> L[:-1] – all elements to the second to last
[2.35, 'spam']
>>> L + [4,5,6] – concatenation between two lists
[2.35, 'spam', 354, 4, 5, 6]

Q: What will be displayed when printing L?


Working with lists
>>> L
[2.35, 'spam', 354]
>>> L.append('NI') – adding the ‘NI’ element o the list
>>> L
[2.35, 'spam', 354, 'NI']
>>> L.pop(2) – removes and returns from the list the element with index
= 2 (third element)
354
>>> L
[2.35, 'spam', 'NI']
Common methods when working with lists
>>> M = ['bb', 'aa', 'cc']
>>> M.sort() #can be used only when the list is homogeneous
>>> M
['aa', 'bb', 'cc']
>>> M.reverse()
>>> M
['cc', 'bb', 'aa']
Common methods when working with lists
>>> my_list=['1','2',1,2]
>>> my_list.sort()

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'int' and 'str'

>>> my_list = [1, 2, 3]


>>> my_list[2] = 5 – we are changing the element from the 3rd position - [1, 2, 5]
>>> del my_list[2] – deletes the element from the 3rd position - [1,2]
>>> 2 in my_list – verifying if 2 is among the elements of the list(True or False) – True
>>> my_list.append(3) – adding individual elements to the list - [1, 2, 3]
>>> max(my_list) - 3
>>> min(my_list) - 1
IndexError exception

>>> 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

Tuples initialization can be done:


• my_tuple = ()
• my_tuple = tuple()
Working with tuples
>>> t = ("Bucharest", 4.953, 3)
>>> t
(Bucharest ', 4.953, 3)
>>> t[0]
Bucharest '
>>> t[2]
3
>>> len(t)
3
Common methods for working with tuples
>>> for item in t:
... print(item)
...
Bucharest
4.953
3
>>> t + (338186.0, 265e9)
(Bucharest ', 4.953, 3, 338186.0, 265000000000.0)
>>> t * 3
(Bucharest ', 4.953, 3, Bucharest ', 4.953, 3, Bucharest ', 4.953, 3)

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

>>>my_dict = {‘key_1’: 10, ‘key_2’: True, ‘key_3’: 20.5}


my_dict[‘key_3’] – 20.5

>>> names_and_ages = [('Alice', 32), ('Bob', 48), ('Charlie', 28),('Daniel',33)]


>>> d = dict(names_and_ages)
{'Charlie': 28, 'Alice': 32, 'Bob': 48, 'Daniel': 33}

>>> stocks = {'GOOG': 891, 'AAPL': 416, 'IBM': 194}


>>> stocks.update({'GOOG': 894, 'YHOO': 25}) - extinde dicționarul adăugând
YHOO și modifică GOOG
>>> stocks
{'IBM': 194, 'YHOO': 25, 'AAPL': 416, 'GOOG': 894}
Working with dictionaries

>>> stocks['GOOG'] – obținem valoarea pentru ‘GOOG’


894
>>> stocks['GOOG'] = '895' - modificăm valoarea pentru ‘GOOG’
>>> stocks
{'IBM': 194, 'YHOO': 25, 'AAPL': 416, 'GOOG': '895'}
Parsing values from a dictionary
>>> stocks
{'IBM': 194, 'YHOO': 25, 'AAPL': 416, 'GOOG': '895'}
>>> for value in stocks.values():
... print(value)
...
194
25
416
895
Parsing keys from a dictionary

>>> for key in stocks.keys():


... print(key)
...
IBM
YHOO
AAPL
GOOG
Parsing keys and values from a dictionary
>>> for key,value in stocks.items():
... print("{key} => {value}".format(key=key, value=value))
...
IBM => 194
YHOO => 25
AAPL => 416
GOOG => 895

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.

You might also like