0% found this document useful (0 votes)
16 views35 pages

Python Data Structures and Essentials

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
16 views35 pages

Python Data Structures and Essentials

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 35

Python Data Structures and

Essentials

T. VAMSIDHAR
Asst. Professor
CSE - H
KLEF
Python Data Structures

2
Python Collections
Python Collections (Arrays)

There are four collection data types in the Python programming language:
• List. ["apple", "banana", "cherry"]
• Tuple ("apple", "banana", "cherry")
• Set {"apple", "banana", "cherry"}
• Dictionary { "brand": "Ford“, "model": "Mustang“, "year": 1964}

Collection type Order/ Changeable/ indexed Duplicate


unordered unchangeable Members
List Order Changeable NA Allow
Tuple Order Unchangeable NA Allow
Set unordered Unchangeable Unindexed No Duplicate
Dictionary unordered Changeable indexed No Duplicate
3
# empty list
List
my_list = []
# list of integers
my_list = [1, 2, 3]
# list with mixed datatypes
my_list = [1, "Hello", 3.4]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

4
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
Example
• Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Access Items
• You access the list items by referring to the index number:
Example
• Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Change Item Value
• To change the value of a specific item, refer to the index number:
Example
• Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
List Length
• To determine how many items a list has, use the len() function:
Example
• Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist)) 5
List Methods

Method Description

append() Adds an element at the end of the list


clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the
extend()
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

6
Tuple
Python Tuples
• A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.
Example
• Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Access Tuple Items
• You can access tuple items by referring to the index number, inside square brackets:
Example
• Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Range of Indexes
• You can specify a range of indexes by specifying where to start and where to end the range.
• When specifying a range, the return value will be a new tuple with the specified items.
Example
• Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
• Note: The search will start at index 2 (included) and end at index 5 (not included).
• Remember that the first item has index 0.
Loop Through a Tuple
• You can loop through the tuple items by using a for loop.
Example
• Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)

7
Join Two Tuples
• To join two or more tuples you can use the + operator:
Example
• Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)
The tuple() Constructor
• It is also possible to use the tuple() constructor to make a tuple.
Example
• Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Tuple Methods
• Python has two built-in methods that you can use on tuples.

Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where it was found

8
Python Sets
Sets
• A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example
• Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
• Note: Sets are unordered, so you cannot be sure in which order the items will appear.
Access Items
• You cannot access items in a set by referring to an index, since sets are unordered the items has no index.
• But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in
keyword.
Example
• Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}

for x in thisset:
print(x)
Example
• Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}

print("banana" in thisset)

9
Add and update Sets
Change Items
• Once a set is created, you cannot change its items, but you can add new items.
Add Items
• To add one item to a set use the add() method.
• To add more than one item to a set use the update() method.
Example
• Add an item to a set, using the add() method:
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
Example
• Add multiple items to a set, using the update() method:
thisset = {"apple", "banana", "cherry"}
thisset.update(["orange", "mango", "grapes"])
print(thisset)
Remove Item
• To remove an item in a set, use the remove(), or the discard() method.
Example
• Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)

10
The set() Constructor
• It is also possible to use the set() constructor to make a set.
Example
• Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)
Set Methods
• Python has a set of built-in methods that you can use on sets.

Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or
more sets
difference_update() Removes the items in this set that are also included in
another, specified set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
intersection_update() Removes the items in this set that are not present in other,
specified set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

11
Python Dictionaries
Dictionary
• A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly
brackets, and they have keys and values.
Example
• Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Accessing Items
• You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
• Get the value of the "model" key:
x = thisdict["model"]
• There is also a method called get() that will give you the same result:
Example
• Get the value of the "model" key:
x = thisdict.get("model")

12
Change Values
• You can change the value of a specific item by referring to its key name:
Example
• Change the "year" to 2018:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
Loop Through a Dictionary
• You can loop through a dictionary by using a for loop.
• When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the
values as well.
Example
• Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
• Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example
• You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Example
• Loop through both keys and values, by using the items() function:
for x, y in thisdict.items():
print(x, y) 13
Adding Items
• Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
• There are several methods to remove items from a dictionary:
Example
• The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)

The dict() Constructor


• It is also possible to use the dict() constructor to make a new dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Dictionary Methods
• Python has a set of built-in methods that you can use on dictionaries.

14
Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and values

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

15
Python If ... Else
If else statement is used for decision making is required in a program
Syntax:
If test_expression:
True statement
else:
False Stement
Example: a = 33
b = 200
if b > a:
print("b is greater than a")
else
print(“a is greater than b”)
Else if statement : ELIF
Syntax
If test_exp:
true statement
elif test2_exp:
true statement
else
false statement
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else: 16
print("a is greater than b")
Shorthand statement
• One line if statement:
if a > b: print("a is greater than b")

Ternary Operators, or Conditional Expressions:

• One line if else statement:


a=2
b = 330
print("A") if a > b else print("B")
• One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

17
Nested If
Nested If
• You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


• if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
• Example
a = 33
b = 200
if b > a:
pass

18
Python Loops

• Loops are used in programming to repeat a specific block of code


• Python has two primitive loop commands:

while loop
While cond_stat:
Body of the while Loop
For loop
for val in sequence:
Body of the for loop

19
While Loops
• The while loop in Python is used to
iterate over a block of code as long as the
test expression (condition) is true.
Syntax:
While Test Expression:
Body of the Loop
Example:
• # Program to add n natural numbers
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1
print("The sum is", sum)
20
While else Statement

With the else statement we can run a block of code once when the condition
no longer is true:
Example
• Print a message once the condition is false:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

21
Nested while loop
Syntax
while expression:
while expression:
statement(s)
statement(s)
The following program uses a nested while loop to find the prime numbers from 2 to 20−

n=5
i=0
while(i<n):
j=0
while(j<i+1):
print("*",end="")
j+=1
print("\r")
i+=1

When the above code is executed, it produces following result −


*
**
***
****
*****

22
For Loops
• The for loop in Python is used to iterate
over a sequence (list, tuple, string) or
other iterable objects. Iterating over a
sequence is called traversal.
Syntax:
for val in sequence:
Body of for the loop
Example:
• # Program to find the sum of all numbers
stored in a list
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
23
Looping through a List and String
Looping Through a List
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
• Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
• The for loop does not require an indexing variable to set beforehand.

Looping Through a String


• Even strings are iterable objects, they contain a sequence of characters:
Example
• Loop through the letters in the word "banana":
for x in "banana":
print(x)

24
Using break and continue
The break Statement
• With the break statement we can stop the loop before it has looped through all the items:
Example
• Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)

The continue Statement


• With the continue statement we can stop the current iteration of the loop, and continue with the
next:
Example
• Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

25
range() function
Using range() Function
• To loop through a set of code a specified number of times, we can use the range() function,
• The range() function returns a sequence of numbers,
starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Example
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
• The range() function defaults to 0 as a starting value.

Setting Range starting value:


• It is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to
6 (but not including 6):
Example
• Using the start parameter:
for x in range(2, 6):
print(x)

Setting Range increment value:


• The range() function defaults to increment the sequence by 1, however it is possible to specify the
increment value by adding a third parameter: range(2, 30, 3):
Example
• Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x) 26
Else in For Loop
• The else keyword in a for loop specifies a block of code to be executed
when the loop is finished:
Example
• Print all numbers from 0 to 5, and print a message when the loop has
ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

27
Nested Loops

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the "outer
loop":
Example
• Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

28
The pass Statement
• for loops cannot be empty, but if you for some reason have a for
loop with no content, put in the pass statement to avoid getting an
error.
Example
for x in [0, 1, 2]:
pass
Note : Don’t use pass for while loop

29
Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
Creating a Function
• In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
• To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
• Information can be passed into functions as arguments.
• Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just
separate them with a comma.
• The following example has a function with one argument (fname). When the function is called, we pass along a first name,
which is used inside the function to print the full name:
Example
def my_function(fname):
print(fname + " Peddada")

my_function(“Venkateswara rao")
my_function(“Siri")
my_function(“Neehar")
30
Function arguments
Parameters or Arguments?
• The terms parameter and argument can be used for the same thing: information that are passed into a function.
• A parameter is the variable listed inside the parentheses in the function definition.
• An argument is the value that are sent to the function when it is called.
Number of Arguments
• By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2
arguments, you have to call the function with 2 arguments, not more, and not less.
Example
• This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function(“venkat", “peddada")
• If you try to call the function with 1 or 3 arguments, you will get an error:
Example
• This function expects 2 arguments, but gets only 1:
def my_function(fname, lname):
print(fname + " " + lname)
my_function(“venkat")
Error message:
Traceback (most recent call last):
File "<string>", line 4, in <module>
TypeError: my_function() missing 1 required positional argument: 'lname'
31
Arbitrary and keyword arguments
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the
function definition.
• This way the function will receive a tuple of arguments, and can access the items accordingly:
Example
• If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function(“venkat", “siri", “neehar")
• Arbitrary Arguments are often shortened to *args in Python documentations.
Keyword Arguments
• You can also send arguments with the key = value syntax.
• This way the order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = “venkat", child2 = “siri", child3 = “neehar")
• The phrase Keyword Arguments are often shortened to kwargs in Python documentations.
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the
parameter name in the function definition.
• This way the function will receive a dictionary of arguments, and can access the items accordingly:
Example
• If the number of keyword arguments is unknown, add a double ** before the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = “venkat", lname = “peddada")
• Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations. 32
Default parameter and return value
Default Parameter Value
• The following example shows how to use a default parameter value.
• If we call the function without argument, it uses the default value:
Example
• def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Return Values
• To let a function return a value, use the return statement:
Example
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
The pass Statement
• function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass
statement to avoid getting an error.
Example
def myfunction():
pass

33
Passing a List as an Argument

• You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside the
function.
• E.g. if you send a List as an argument, it will still be a List when it reaches
the function:
Example
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)

34
Recursion
Recursion
• Python also accepts function recursion, which means a defined function can call itself.
• This has the benefit of meaning that you can loop through data to reach a result.
• The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never
terminates, or one that uses excess amounts of memory or processor power.
• In this example, factorial () is a function that we have defined to call itself ("recurse").
We use the n variable as the data, which decrements (-1) every time we recurse.
The recursion ends when the condition is equal to 1 or 0.

Example
Recursion Example

# program to find factorial of given number


def factorial(n):
If(n==1 or n==0)
return 1
else:
return (n*factorial(n-1))
# Driver Code
num = 5;
print("Factorial of", num, "is", factorial(num))

# single line to find factorial


• return 1 if (n == 1 or n == 0) else n * factorial(n - 1);

35

You might also like