Data Structures Python
Data Structures Python
Control Structures
INTRODUCTION
• Programs are written for the solution to the
real world problems.
• A language should have the ability to control
the flow of execution so that at different
intervals different statements can be
executed.
• A language which supports the control
structures is called a structured
programming language
TYPES OF CONTROL STRUCTURES
1. SEQUENCE
2. SELECTION
3. ITERATION OR LOOPING
: Colon Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
CONDITIONAL CONSTRUCT – if else STATEMENT
FLOW CHART
False
Condition ? Statement 1 Statement 2
Main True
Body
Statement 1
else
Statement 2 body
CONDITIONAL CONSTRUCT – if else STATEMENT
else is missing,
it is an optional
statement
OUT PUT
EXAMPLE – if else STATEMENT
: Colon Must
else is
used
OUT PUT
Python Data
Structures
Built in Types
• Lists
• Tuples
• Sets
• Dictionaries
Terms We'll Use
• List notation
• List.extend(L)
– Extend the list by appending all in the given list L
• List.insert(I,x)
– Inserts an item at index I
• List.remove(x)
– Removes the first item from the list whose value is x
Examples of other methods
• a = [66.25, 333, 333, 1, 1234.5] //Defines List
– print (a.count(333), a.count(66.25), a.count('x') ) //calls method
– 2 1 0 //output
• print(a.sort())
– [ 1, 66.25, 333, 333, 1234.5] //Output
• a.index(333)
– print(a.index(333)) //Returns the first index where the given value appears
– 1//output
• print(a[0]) Output?????????
• print(a[1:3]) Output???????
Tuples
Tuples are ordered, immutable collections of
elements.
• a.index(333)
– print(a.index(333) )//Returns the first index where the given value
appears
– 1 //output
• print(a[0])Output?????????
• print(a[0:3]) Output???????
mySet = set(['a‘])
# Add an element:
mySet.add(‘e')
print(mySet)
mySet.add(‘a')
print(mySet)
Output ???????????
#Remove an element:
mySet.remove('b')
print(mySet)
Output ????????????
Sets
There is also support for combining sets.
Returns a new set with all the elements from both
sets:
mySet.union(someOtherSet)
Returns a new set with elements that were in both
sets:
mySet.intersection(someOtherSet)
Tons more methods can be found here:
https://docs.python.org/3/tutorial/datastructures.html
Dictionaries
Lists can be viewed as a structure that map
indexes to values.
e.g.
myDict["hello"] = 10
^ ^
Key Value
Dictionaries
If we want to get just the keys, or just the values,
there's a function for that!
listOfKeys = myDict.keys()
listOfValues = myDict.values()
Dictionaries
e.g
dict= {‘name’: “Rise”, ‘code’:8, ‘dept’: “CS”}
Determine the Output of the following:
print(dict[‘name’])
print(dict)
print(dict.values())
print(dict.keys())
Dictionaries
Homework