0% found this document useful (0 votes)
38 views7 pages

CO1010 ProgrammingforEngineersI Jun2024 Handout9 Ds

Programming python.
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)
38 views7 pages

CO1010 ProgrammingforEngineersI Jun2024 Handout9 Ds

Programming python.
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/ 7

CO1010 Programming

for Engineers I
Data Structures
Dr. Eng. Sampath Deegalla
Department of Computer Engineering
Faculty of Engineering
University of Peradeniya
September 6th, 2024

Data Structures Lists

A list holds an ordered collection of items.


Data structures are structures which can hold some data
Items should be enclosed in square brackets
together.
After creating list, one can add, remove or search for items.
There are four built-in data structures in Python: list, tuple,
dictionary and set. Items can be added or removed in the list. Therefore, list is a
mutable data type.

1 23 2 23
Example Example cont.

# creating a list with a set of numbers


numberList = [11, 2, 23, 45, 15]

# print the list


print(numberList) # changing values in the list
numberList[1] = 20 # change the second item to 20
# print each item in the list
for i in numberList: # sorting the list
print(i) numberList.sort() # ascending
numberList.sort(reverse=True) # descending
# length of the list
print(len(numberList)) # removing an item
del numberList[0] # remove the item based on the location
# access the first item of the list numberList.remove(100) # remove the item based on the value
print(numberList[0])
# removing the list
# adding an item to the end of the list del numberList
numberList.append(29)

# adding an item to the specific place in the list


numberList.insert(1,20) # add 20 as the second item

3 23 4 23

List Methods Exercise

Create a list with the following items


▶ apple, mango, carrot and banana
Function Description
len() Returns the number of items in the list Print the length of the list
append() Add item to the end of the list Print the items on the list
insert(0,100) Add 0 in the 0th index, i.e., as the first item
sort() Sort the list Add rice to the list
del listName[i] Delete the ith item in the list ‘listName’ Print the list again
remove(100) Remove 100 from the list
help(list) Get more information on lists in Python Sort the list
help(list.append) Get more information on append method in Print only the first item of the list
lists
Remove the first item of the list
Print the list

5 23 6 23
Nested Lists Matrices

Python allows to store any data item in a list. Therefore, you can Nested lists are often used to represent
also store list inside a list (Nested List). matrices. E.g.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
 
myShoppingList = [] # define a empty list 1 2 3
myShoppingList.append(['apple',5]) # add a list to the list
print(myShopping[0][1]) # print number of apples
 4 5 6  To select a row
myShoppingList[0][1]=7 # change number of apples to 7 7 8 9 matrix[1]
print(myShoppingList) # print the whole list
To select an element
matrix[1][1]

7 23 8 23

Tuple Example

# creating a tuple with a set of numbers


numberTuple = (11, 2, 23, 45, 15)

# print the tuple


print(numberTuple)
A tuple holds an ordered collection of items. It is similar to
# print each item in the tuple
lists. for i in numberTuple:
print(i)
Items should be enclosed in round brackets
After creating tuple, one can not add, remove or change # length of the tuple
print(len(numberTuple))
items (Read only list).
Therefore, tuple is an immutable data type. # access the first item of the list
print(numberTuple[0])

# delethe the tuple


del numberTuple

9 23 10 23
Tuple Methods Set

Method Name Meaning


A set holds unordered collection of unique items.
count() Returns the number of times a specified value
▶ Items should be enclosed in curly brackets.
occurs in a tuple
▶ Since the items are unordered there is no index to access
index() Return the first index of a value
len() Returns the number of items in the tuple items.
del tupleName Delete the tuple ▶ Items cannot be changed but new items can be added to the
help(tuple) Get more information on tuples in Python set.

11 23 12 23

Example Example cont.

# creating a set with a set of numbers


numberSet = {11, 2, 23, 45, 15}

# print the set


print(numberSet)

# print each item in the set # remove an item in the set


for i in numberSet: numberSet.remove(2) # error if not exist
print(i) numberSet.discard(2) # no error if not exist

# length of the set # delethe the set


print(len(numberSet)) del numberSet

# add an item to the set


numberSet.add(6)

# add multiple items to the set


numberSet.update([6, 7, 8])

13 23 14 23
Set Methods Dictionary

Method Name Meaning


add() Add element to the set A dictionary holds a set of items like a list.
discard() Remove an item from the set. No error if not
However, rather than accessing elements using index, it uses
exist in the set.
len() Returns the number of items in the set a fixed key
del setName Delete the set It contain key-value pairs.
help(set) Get more information on sets in Python

15 23 16 23

Example Example cont.

# create a dictionary
numberDict = {
'one' : 'ichi',
'two' : 'ni', # length of the dictionary
'three' : 'san' print(len(numberDict))
}
# print the dictionary # access key one
print(numberDict) print(numberDict['one'])
print(numberDict.get('one'))
# print keys in the dictionary
for i in numberDict: # add items
print(i) numberDict['four']='yon'

# print values in the dictionary #change the value in key 'four' as 'shi'
for i in numberDict.values(): numberDict['four'] = 'shi'
print(i)
# remove item with key 'two'
# print items in the dictionary del numberDict['two']
for i in numberDict.items():
print(i)

17 23 18 23
Dictionary Methods Strings

Method Name Meaning


A string is a sequence of characters enclosed in single
get() Return the value of the specified key
items() Returns a list of key-value pair quotation marks or double quotation marks.
keys() Return a list of keys Using an index, the character at a certain position can be
len() Returns the number of items in the dictionary obtained.
update() Update the dictionary with multiple items
del dictName Delete the dictionary Note: Strings are immutable, i.e., the content could not be
help(dict) Get more information on dictionary in Python altered.

19 23 20 23

Example Slicing Strings


Slice strings using [start:stop:step], the default value for step
is 1
s= ’ D i a l o g ’
s= ’ D i a l o g ’
index → 0 1 2 3 4 5
→ forward indexing Try the following
-6 -5 -4 -3 -2 -1
← backward indexing
s[0:4] s[:4]

Try the following s[3:6] s[3:]


s[0:6] s[0:len(s)] s[:]
s[0] s[3] s[5]
s[3:6:2] s[3:len(s):2] s[3::2]
s[-6] s[-3] s[-1]
s[0:6:1] s[0:len(s):1] s[::]
s[-1:-7:-1] s[-1:-(len(s)+1):-1] s[::-1]

21 23 22 23
Strings cont.

s = 'Dialog'

# print individual character at a time


for i in range(len(s)):
print(s[i])

for char in s:
print(char)

23 / 23

You might also like