You are on page 1of 20

3 – DATA STRUCTURES

Parham Kazemi
University of Isfahan, Computer Eng. Faculty
ACM Student Chapter
pkazemi3@gmail.com
DATA STRUCTURES

Data
Structures

Non
Primitive
Primitive

int float List Tuple

string bool Dictionary Set

2
LISTS

• The list is the most versatile datatype available in Python which can be written as a list
of comma-separated values (items) between square brackets.
• Items in a list don’t need to be of the same type.

• CREATING A LIST
• >>> l1 = [1, 2.0, 3+4j, ‘hello’, [1, 2, 3]]

• You can also convert an iterable object to a list:


• >>> l2 = list(‘hello’)
• >>> l3 = list(range(10))

• ACCESSING LISTS
• Just like indexing and slicing in strings.
3
LISTS

• UPDATING LISTS
• Assign a value to an index:
>>> l = [1, 2, 3, 4]
>>> l[0] = 10
>>> l[1:4] = [20, 30, 40]
>>> print(l)
[10, 20, 30, 40]

• Use the append method to add new items:


>>> l.append(50)
>>> l += [60]
>>> print(l)
[10, 20, 30, 40, 50, 60]
4
LISTS

• DELETING LIST ITEMS


• Using either the del keyword or a lists .remove method:
>>> l = [1, 2, 3, 4, 5]
>>> del l[0]
>>> print(l)
[2, 3, 4, 5]
>>> l.remove(3)
>>> print(l)
[2, 4, 5]
>>> l.remove(l[1])
>>> print(l)
[2, 5]

5
LISTS

• LIST OPERATIONS
• List concatenation (using +):
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> l1 + l2
[1, 2, 3, 4, 5, 6]

• Repetition (using *):


>>> l = [1] * 5
>>> l
[1, 1, 1, 1, 1]

6
LISTS

LIST FUNCTIONS
• >>> l = [1, 2, 3, 4, 5]

• Length of a list:
>>> len(l)
5

• Maximum and minimum values of a list:


>>> max(l)
5
>>> min(l)
1
7
LISTS

LIST METHODS

METHOD DESCRIPTION

l.append(val) Appends val to the list l

l.extend(seq) Appends the contents of seq to the list l

Returns the count of how many times val


l.count(val)
occurs in l

l.index(val) Returns the lowest index in l that val appears

l.insert(index, val) Inserts val into list l at offset index

l.reverse() Reverses list in place

l.sort() Sorts list in place

8
TUPLES

• The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] )
and their elements and size can be changed, while tuples are enclosed in parentheses ()
and cannot be updated.Tuples can be thought of as read-only lists.

>>> t = (1, ‘2’, [3])


>>> t[0] = 2 # error
>>> t = t + (3,) # t = (1, ‘2’, [3], 3)
>>> t[2][0] = 0 # t = (1, ‘2’, [0])

>>> t = t + [4]
TypeError: can only concatenate tuple (not "list") to tuple

9
SETS

• A Set is an unordered collection data type that is iterable, mutable, and has no
duplicate elements.

>>> s1 = {1,2,3}
>>> s2 = {3,1,2}
>>> s1 == s2 # Sets are unordered
True
>>> s3 = set([1,1,2,3,3,1,2,2])
>>> s1 == s2 == s3
True

10
SETS

• Sets support:
• x in set
• len(set)
• for x in set
• Set is an unordered collection and does not record element position or order
of insertion.
• Sets do not support indexing, slicing, or other sequence-like behavior.
>>> s = {1,2,3,4}
>>> s[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
11
SETS

• There are currently two built-in set types, set, and frozenset.
• The set type is mutable - the contents can be changed using methods like add() and
remove().
• Since it is mutable, it has no hash value and cannot be used as either a dictionary key
or as an element of another set.
• The frozenset type is immutable and hashable - its contents cannot be altered after it
is created; it can, therefore, be used as a dictionary key or as an element of another
set.

12
SETS

METHOD DESCRIPTION

.add(val) Inserts val into the set

Removes val from the set (raises KeyError


.remove(val)
if val isn’t present)

Removes the first value from the set and


.pop()
returns it

.discard(val) Removes val from the set (if present)

13
SETS

OPERATION SET THEORY EQUIVALENT

A&B A∩B

A|B A∪B

A-B A-B

A^B A∆B

A <= B True if A ⊆ B

A<B True if A ⊂ B

A >= B True if A ⊇ B

A>B True if A ⊃ B

14
DICTIONARIES

• The dictionary is Python’s built-in mapping type.


• Dictionaries map keys to values and these key-value pairs provide a useful way to
store data in Python.
• Each key is separated from its value by a colon (:), the items are separated by commas,
and the whole thing is enclosed in curly braces.
• An empty dictionary without any items is written with just two curly braces: {}

>>> me = {'username': ‘random_redcoat’,


'online': True,
'followers’: 490 }

15
DICTIONARIES

• The dictionary is Python’s built-in mapping type.


• Dictionaries map keys to values and these key-value pairs provide a useful way to store data
in Python.
• Each key is separated from its value by a colon (:), the items are separated by commas, and
the whole thing is enclosed in curly braces.
• An empty dictionary without any items is written with just two curly braces: {}
• Keys are unique within a dictionary while values may not be.
• The values of a dictionary can be of any type, but the keys must be of an immutable data type

>>> me = {'username': ‘random_redcoat’,


'online': True,
'followers’: 490 }
>>> me['username’]
‘random_redcoat’
16
DICTIONARIES

• Updating dictionaries
>>> d = {‘A’: 1, ‘B’: 2, ‘C’: 3}
>>> d[‘D’] = 4 # Adding new values
>>> d[‘A’] = 5 # Updating current value
>>> d
{‘A’: 5, ‘B’: 2, ‘C’: 3, ‘D’: 4}

>>> d.update({‘a’: 10, ‘b’: 20})


>>> d
{‘a’: 10, ‘b’: 20, ‘A’: 5, ‘B’: 2, ‘C’: 3, ‘D’: 4}

17
DICTIONARIES

• Updating dictionaries
>>> d = {‘A’: 1, ‘B’: 2, ‘C’: 3}
>>> d[‘D’] = 4 # Adding new values
>>> d[‘A’] = 5 # Updating current value
>>> d
{‘A’: 5, ‘B’: 2, ‘C’: 3, ‘D’: 4}
>>> d.update({‘a’: 10, ‘b’: 20})
>>> d
{‘a’: 10, ‘b’: 20, ‘A’: 5, ‘B’: 2, ‘C’: 3, ‘D’: 4}
>>> del d[‘a’]
>>> a
{‘b’: 20, ‘A’: 5, ‘B’: 2, ‘C’: 3, ‘D’: 4}
18
DICTIONARIES

METHOD DESCRIPTION
Returns value of key if present, else returns
.get(key, default=None)
default
Similar to get(), but will set
.setordefault(key, default=None) dict[key]=default if key is not already in
dict
Returns a list of tuple pairs containing all
.items()
(key, values)
.keys() Returns a list of the dictionary’s keys

.values() Returns a list of the dictionary’s values

19
DICTIONARIES

Example
Suppose we have a number of episodes of a tv show named like this:

TV.Show.Season1.Episode1.EpisodeTitle.mp4

Write a Python program that groups all episodes of a single season in a dictionary format:

{1: {1: ‘Title1’, 2: ‘Title2’, …},


2: {1:’ Title1’, 2: ‘Title2’, …},
…}

20

You might also like