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

Final InOne Lecture 9, 10 and 11 Data Structures

Uploaded by

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

Final InOne Lecture 9, 10 and 11 Data Structures

Uploaded by

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

DATA

STRUCTURES
Data Structures In Python
KEY CONCEPTS
Key Concepts that we are going to
see here
 List -- VarName = []
 Dictionary – Dict --- VarName = {}
 Tuple -- VarName = ()
WHAT ARE DATA
STRUCTURES?
In computer science, a data
structure is a particular way of
organizing data in a computer so that
it can be used efficiently.
LISTS
A List is a kind of Collection

A collection allows us to put many values in a


single “variable”

A collection is nice because we can carry


many values around in one convenient
package.
LIST

friends_cast = [‘Chandler’, ‘Phoebe’,


‘Joey’]

marks = [12, 15, 9, 12, 20, 19]


LIST CONSTANTS
 List constants are surrounded by square
brackets and the elements in the list are
separated by commas.
 A list element can be any Python object
- even another list
 A list can be empty
EXAMPLES

>>> print([1, 24, 76] )

[1, 24, 76.0]

>>> print(['red', 'yellow', 'blue'] )

['red', 'yellow', 'blue']


EXAMPLES

>>> print([ 1, [5, 6], 7] )

[1, [5, 6], 7]

>>> print( [] )

[]
GO THROUGH THE LIST
5
for i in [5, 4, 3, 2, 1] : 4
print(i) 3
2
print('Blastoff!‘)
1
Blastof
f!
LIST TRAVERSAL

Simpsons= [‘Homer', ‘Bart', ‘Lisa’,


‘Marge’]

for character in Simpsons:


print(character, ‘is in the Simpsons
family’)
HOW LONG IS A LIST?
The len() function takes a list as a parameter
and returns the number of elements in the list

Actually len() tells us the number of elements


of any set or sequence (i.e. such as a string...)
LIST TRAVERSAL
car_makers = [‘Ford’, ‘Toyota’, ‘BMW’]

for car in range(len(car_makers)):


print(car_makers[car])
Output:
Ford
Toyota
BMW
THE in OPERATOR

>>> ‘Ford’ in [‘Ford’, ‘Toyota’,


‘BMW’]
True
LIST OPERATIONS
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b # + Adding Lists
Together
>>> c
[1, 2, 3, 4, 5, 6]
LIST OPERATIONS
>>> [0] * 4 # + in this case didn’t
work

[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
LIST OPERATIONS
>>> a_list = ["a", "b", "c", "d", "e",
"f"]
>>> a_list[1:3]
['b', 'c']
>>> a_list[:4]
['a', 'b', 'c', 'd']
LOOKING INSIDE LISTS
Just like strings, we can get at any single
element in a list using an index specified
in square brackets
‘Homer ‘Marge
‘Bart' ‘Lisa’
’ ’
0 1 2 3
UPDATING LISTS
friends_cast = [‘Chandler’, ‘Phoebe’, ‘Joey’]

friends_cast[0] = ‘Monica’ # this code replace the list item


found at index [0] i.e Chandler

print(friends_cast)
Output:
['Monica', 'Phoebe', 'Joey']
MUTABILITY: LIST VS
STRINGS
Lists are mutable

Strings are immutable

Note: In Python, a data type is mutable if its values can be changed, updated, or

modified after the data type has been created. In other words, once an object of the
mutable data type is initialized, you can update its content without creating a new object
STRING
>>> my_string = "TEST"
>>> my_string[2] = "X"
B/C String is immutable
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
my_string[2] = 'x'
TypeError: 'str' object does not support item assignment
DEEP COPY & SHALLOW
COPY
>>> game_of_thrones = [‘Targaryen’, ‘Stark’]

>>> got_families = game_of_thrones


>>> got_families[0] = ‘Baratheon’
>>> print(game_of_thrones)
Output: ['Baratheon', 'Stark']
DATA
STRUCTURES
Lecture Slide-10
REVIEW: WHAT ARE DATA
STRUCTURES?
In computer science, a data
structure is a particular way of
organizing data in a computer so that
it can be used efficiently.
REVIEW: LISTS
 A List is a kind of Collection

 A collection allows us to put many values in a

single “variable”
 A collection is nice because we can carry many

values around in one convenient package.


REVIEW: LIST OPERATIONS
>>> a_list = ["a", "b", "c", "d", "e",
"f"]
>>> a_list[1:3]
['b', 'c']
>>> a_list[:4]
['a', 'b', 'c', 'd']
REVIEW: LOOKING INSIDE
LISTS
Just like strings, we can get at any single
element in a list using an index specified
in square brackets
‘Homer ‘Marge
‘Bart' ‘Lisa’
’ ’
0 1 2 3
LIST ARGUMENTS

Write a function that determines


the length of a list
def list_length(lst):
return len(lst)
example_list = [1, 2, 3, 4, 5]
print("The length of the list is:", list_length(example_list))
LIST APPEND METHOD

>>> t1 = [1, 2]

>>> t1.append(3)

>>> print(t1)

[1, 2, 3]
LIST INSERT METHOD
Syntax: list.insert(position, element)

>>> k = [1, 2]

>>> k.insert (2,4)

>>> print(k)

[1, 2, 4]
LIST INSERT METHOD

>>> l = [1, 2]

>>> l.insert (23,4)

>>> print(l)

[1, 2, 4] # b/c thier is no positon 23, it added at end


LIST INSERT METHOD

>>> l = [1, 2]

>>> l.insert (1,4)

>>> print(l)

[1, 4, 2]
LIST METHODS
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print(t1)
[1,2,3]
>>> print(t2)
None #append work for the list itself not to uppend and assign at the same
time
‘is’ OPERATOR
Given two strings

a = ‘banana’
b = ‘banana’

We know that a and b both refer to a


string.
‘is’ OPERATOR
>>> a = 'banana'
>>> b = 'banana'
>>> a == b
True
‘is’ OPERATOR
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
‘is’ OPERATOR
>>> a = [1,2]
>>> b = [1,2]
>>> a == b
True
‘is’ OPERATOR
>>> a = [1,2]
>>> b = [1,2]
>>> a is b
False
Note: The is operator in Python is a comparison operator used to check if two objects refer
to the same memory location. This means that the is operator checks whether two variables or
objects have the same identity, rather than just the same value
DEBUGGING
t = [1,2]
# add element 4 to list t
t.append([4]) # append [4]
t = t.append(4) // none
t + [4] //This didn’t work
t = t + 4 //This didn’t work
DICTIONARY
DICTIONARY
Dictionary is like a list, but more general.

In a list, the indices have to be integers;

in a dictionary they can be (almost) any


type.
DICTIONARY

A dictionary is a mapping between


KEYS and set of Values.

key-value pair
DICTIONARY
 Lists index their entries based on the position

in the list.
 Dictionaries are like bags - no order

 So we index the things we put in the dictionary

with a “lookup tag”


DICTIONARY

>>> eng2sp = {}
dict()

>>> print(eng2sp)

{}
DICTIONARY

>>> eng2sp[‘one’] = ‘uno’

>>> print(eng2sp)

{'one': 'uno'}
DICTIONARY

>>> eng2sp = {'one': 'uno', 'two': 'dos',


'three': 'tres'}

>>> print(eng2sp)

{'three': 'tres', 'two': 'dos', 'one': 'uno'}


DICTIONARY

The order of the key-value pairs is not the


same. In fact, if you type the same
example on your computer, you might get
a different result. In general, the order of
items in a dictionary is unpredictable.
DICTIONARY

>>> item_price = {}

>>> item_price[‘milk’] = 10

>>> print(item_price[‘milk’])

10
DICTIONARY

>>> item_price = {}

>>> item_price[‘milk’] = 10

>>> print(item_price[‘sugar’])

KeyError: ‘sugar’
DICTIONARY

>>> number_of_days = {‘January’:


31, ‘February’: 28, ‘March’: 31}

>>> number_of_days[‘February’]
DEBUGGING
Key Error

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

KeyError: 3
ITERATION ON
DICTIONARIES
Even though dictionaries are not stored in
order, we can write a for loop that goes
through all the entries in a dictionary -
actually it goes through all of the keys in the
dictionary and looks up the values
ITERATION
eng2sp = {'one': 'uno', 'two': 'dos',
'three': 'tres'}

for k in eng2sp:
print(k)
ITERATION: VALUES
eng2sp = {'one': 'uno', 'two': 'dos',
'three': 'tres'}

for k in eng2sp:
print(eng2sp[k])
‘in’ OPERATOR
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three':
'tres'}

>>> ‘one’ in eng2sp


True
>>> ‘uno’ in eng2sp
False
DEMO: CHARACTER
COUNTER
(HISTOGRAM)
WHAT DATA TYPES CAN NOT
BE KEYS
RETRIEVING LISTS OF KEYS
AND VALUES
>>> counts.keys()

>>> counts.values()

>>> counts.items()
DATA
STRUCTURE
From Lecture 11
REVIEW: DICTIONARY

A dictionary is a mapping between


KEYS and set of Values.

key-value pair
REVIEW

>>> eng2sp[‘one’] = ‘uno’

>>> print(eng2sp)

{'one': 'uno'}
TUPLES
TUPLES

 a sequence of values

 are indexed by integers

>>> t = ‘a’, ‘b’, ‘c’


TUPLES

 Tuples are Immutable

>>> t = (‘a’, ‘b’, ‘c’)


TUPLES

>>> t1 = ()

>>> t2==(1,)
(1)
TUPLE ASSIGNMENT

a, b = 2, 3
RETURN VALUES

def divmod(a,b):
return a//b, a%b
DICTIONARIES & TUPLES

>>> d = {‘a’: 12, ‘b’: 18}

>>> t = d.items()

[(‘b’,18),(‘a’,12)]
LOOPING

for key, value in d.items():


print(key, ‘==>’, value)

You might also like