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

Python Unit 3 Notes

Uploaded by

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

Python Unit 3 Notes

Uploaded by

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

lOMoARcPSD|20730777

Python unit-3 Notes

Computer System Security/Python Programming (Dr. A.P.J. Abdul Kalam Technical


University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Harshini S (harshini1165@gmail.com)
lOMoARcPSD|20730777

Unit-III
Function
Python Functions is a block of statements that return the specific task.

The idea is to put some commonly or repeatedly done tasks together and make a function so that
instead of writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again. You can pass data, known as parameters, into a
function. A function can return data as a result.

Syntax:

The following elements make up define a function, as seen above.

o The beginning of a function header is indicated by a keyword called def.


o function_name is the function's name that we can use to separate it from others. We will use
this name to call the function later in the program. The same criteria apply to naming
functions as to naming variables in Python.
o We pass arguments to the defined function using parameters. They are optional, though.
o The first statement of a function can be an optional statement - the documentation string of
the function or docstring.
o The function header is terminated by a colon (:).
o The body of the function is made up of several valid Python statements. The indentation
depth of the whole code block must be the same.
o We can use a return expression to return a value from a defined function.

Creating a Function

In Python a function is defined using the def keyword:

Example

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

def my_function():
print("welcome to python ")

Calling a Function

To call a function, use the function name followed by parenthesis:

Example
def my_function():
print("welcome to python")
# call a function
my_function()

From a function's perspective:

A parameter is the variable listed inside the parentheses in the function definition.

An argument is the value that is sent to the function when it is called.

Defining and calling a function with parameters

If you have experience in C/C++ or Java then you must be thinking about the return type of the
function and data type of arguments. That is possible in Python as well (specifically for Python 3.5
and above).
Syntax: Python Function with parameters
def function_name(parameter: data_type) -> return_type:
"""Doctring"""
# body of the function
return expression
The following example uses arguments that you will learn later in this article so you can come back
on it again if not understood. It is defined here for people with prior experience in languages like
C/C++ or Java.

def add(num1: int, num2: int) -> int:


"""Add two numbers"""
num3 = num1 + num2

return num3

num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Output:
The addition of 5 and 15 results 20.
Arguments of a Python Function
Arguments are the values passed inside the parenthesis of the function. A function can have any
number of arguments separated by a comma.
In this example, we will create a simple function to check whether the number passed as an
argument to the function is even or odd.

# A simple Python function to check


# whether x is even or odd

def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# call the function


evenOdd(2)
evenOdd(3)

Types of Arguments
Python supports various types of arguments that can be passed at the time of the function call. Let’s
discuss each type in detail.
Default arguments
A default argument is a parameter that assumes a default value if a value is not provided in the
function call for that argument. The following example illustrates Default arguments.

# Python program to demonstrate default arguments

def myFun(x, y=50):


print("x: ", x)
print("y: ", y)

# We call myFun() with only argument)


myFun(10)

Output
x: 10
y: 50

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Like C++ default arguments, any number of arguments in a function can have a default value. But
once we have a default argument, all the arguments to its right must also have default values.
Keyword arguments
The idea is to allow the caller to specify the argument name with values so that caller does not need
to remember the order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='Mukesh', lastname='Jha')
student(lastname='Jha', firstname='Mukesh')

Output
Mukesh Jha
Mukesh Jha

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)

output:
apple
banana
cherry
Return statement in Python function
The Python return statement is used to return a value from a function. The user can only use the return
statement in a function. It cannot be used outside of the Python function. A return statement includes
the return keyword and the value that will be returned after that.
Syntax:
return [expression_list]

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

The return statement can consist of a variable, an expression, or a constant which is returned to the
end of the function execution. If none of the above is present with the return statement a None
object is returned.
Example: Python Function Return Statement

def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

print(square_value(2))
print(square_value(-4))

Output
4
16

Program to find factorial of a number


num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print(" Factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

output:
Enter a number: 10
The factorial of 10 is 3628800

Recursion

The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called a recursive function. Recursion is an amazing technique with the
help of which we can reduce the length of our code and make it easier to read and write.
Properties of Recursion
• Performing the same operations multiple times with different inputs.
• In every step, we try smaller inputs to make the problem smaller.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

• Base condition is needed to stop the recursion otherwise infinite loop will occur.
What is the base condition in recursion?
In the recursive program, the solution to the base case is provided and the solution to the bigger
problem is expressed in terms of smaller problems.

int fact(int n)
{
if (n < = 1) // base case
return 1;
else
return n*fact(n-1);
}
In the above example, the base case for n < = 1 is defined and the larger value of a number can be
solved by converting to a smaller one till the base case is reached.
Program to find factorial of a number using recursion

def factorial(x):

if x == 1:
return 1
else:
# recursive call to the function
return (x * factorial(x-1))

num = int(input("Enter a number: "))

# call the factorial function


result = factorial(num)
print("The factorial of", num, "is", result)

Output:
Enter a number: 5
The factorial of 5 is 120

Python program to display the Fibonacci sequence using recursion

def fib(n):
if n <= 1:
return n

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

else:
return(fib(n-1) + fib(n-2))

nterms = int(input("enter the number of terms"))

# check if the number of terms is valid


if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(fib(i))

Output
enter the number of terms8
Fibonacci sequence:
0
1
1
2
3
5
8
13

Scope and Lifetime of Variables

The scope of a variable refers to the domain of a program wherever it is declared.

Local (or function) scope

• It is the code block or body of any Python function or lambda expression.

• This Python scope contains the names that you define inside the function.

• These names will only be visible from the code of the function.

• It’s created at function call, not at function definition, so we have as many different local scopes as
function calls.

• It is applicable if we call the same function multiple times, or recursively.

• Each call will result in a new local scope being created.

Global (or module) scope

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

• It is the top-most scope in a Python program, script, or module.

• This scope contains all of the names that are defined at the top level of a program or a module.

• Names in this Python scope are visible from everywhere in your code.

Here's a simple example of a variable's scope within a function.

Let’s look at an example that demonstrates scope ideas. Suppose we write the following code in a
module file:

# global scope
X = 99 # X and func assigned in module: global

def func(Y): # Y and Z assigned in function: locals


# local scope
Z=X+Y # X is not assigned, so it's a global
return Z

func(1) # func in module: result=100

This module, and the function it contains, use a number of names to do their business. Using Python’s
scope rules, we can classify the names as follows:

Global names: X, func


X is a global because it’s assigned at the top level of the module file; it can be referenced
inside the function without being declared global. func is global for the same reason;
the def statement assigns a function object to the name func at the top level of the module.
Local names: Y, Z
Y and Z are local to the function (and exist only while the function runs), because they are
both assigned a value in the function definition

Python Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Lambda functions can take any number of arguments:

Example

Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))
Example

Summarize argument a, b, and c and return the result:

x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
Why Use Lambda Functions?

The power of lambda is better shown when you use them as an anonymous function inside another
function.

Say you have a function definition that takes one argument, and that argument will be multiplied with
an unknown number:

def myfunc(n):
return lambda a : a * n

Use that function definition to make a function that always doubles the number you send in:

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)

print(mydoubler(11))

Or, use the same function definition to make a function that always triples the number you send in:

Example
def myfunc(n):
return lambda a : a * n

mytripler = myfunc(3)

print(mytripler(11))

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Or, use the same function definition to make both functions, in the same program:

Example
def myfunc(n):
return lambda a : a * n

mydoubler = myfunc(2)
mytripler = myfunc(3)

print(mydoubler(11))
print(mytripler(11))

Anonymous functions in Python Function


In Python, an anonymous function means that a function is without a name. As we already know the
def keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.

# Python code to illustrate the cube of a number


# using lambda function

def cube(x): return x*x*x

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))

Output
343
343
Python Function within Functions
A function that is defined inside another function is known as the inner function or nested function.
Nested functions are able to access variables of the enclosing scope. Inner functions are used so that
they can be protected from everything happening outside the function.

# Python program to demonstrate accessing of variables of nested functions

def f1():
s = 'My name is bandana'

def f2():
print(s)

f2()

f1()

Output

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

My name is bandana

Strings : Length of the string and perform Concatenation and Repeat operations in it. Indexing
and Slicing of Strings.

A string is a sequence of characters. For example, "hello" is a string containing a sequence of

characters 'h', 'e', 'l', 'l', and 'o'.

We use single quotes or double quotes to represent a string in Python. For example,

# create a string using double quotes


string1 = "Python programming"

# create a string using single quotes


string1 = 'Python programming'

Here, we have created a string variable named string1. The variable is initialized with the

string Python Programming.

You can assign a multiline string to a variable by using three quotes:

You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Strings indexing and splitting

Like other languages, the indexing of the Python strings starts from 0. For example, The string
"HELLO" is indexed as given in the below figure.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Consider the following example:

1. str = "HELLO"
2. print(str[0])
3. print(str[1])
4. print(str[2])
5. print(str[3])
6. print(str[4])
7. # It returns the IndexError because 6th index doesn't exist
8. print(str[6])

Output:

H
E
L
L
O
IndexError: string index out of range

As shown in Python, the slice operator [] is used to access the individual characters of the string.
However, we can use the : (colon) operator in Python to access the substring from the given string.
Consider the following example.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

H E L L O

-5 -4 -3 -2 -1

Slicing

You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the string.

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])
output:
llo

The first character has index 0.

Slice From the Start

By leaving out the start index, the range will start at the first character:

Example

Get the characters from the start to position 5 (not included):

b = "Hello, World!"
print(b[:5])

output

Hello

Slice To the End

By leaving out the end index, the range will go to the end:

Example

Get the characters from position 2, and all the way to the end:

b = "Hello, World!"
print(b[2:])

Output

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

llo, World!

Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example

Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2):

b = "Hello, World!"
print(b[-5:-2])
output
orl

Python - Modify Strings

Python has a set of built-in methods that you can use on strings.

Upper Case
Example

The upper() method returns the string in upper case:

a = "Hello, World!"
print(a.upper())
Lower Case
Example

The lower() method returns the string in lower case:

a = "Hello, World!"
print(a.lower())
Remove Whitespace

Whitespace is the space before and/or after the actual text, and very often you want to remove this
space.

Example

The strip() method removes any whitespace from the beginning or the end:

a = " Hello, World! "


print(a.strip()) # returns "Hello, World!"
Replace String

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Example

The replace() method replaces a string with another string:

a = "Hello, World!"
print(a.replace("H", "J"))
output
Jello, World!

Split String

The split() method returns a list where the text between the specified separator becomes the list items.

Example

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(","))
output
'Hello', ' World!'

String Concatenation

To concatenate, or combine, two strings you can use the + operator.

Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)
Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

String Format

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

As we learned in the Python Variables chapter, we cannot combine strings and numbers like this:

Example
age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string where
the placeholders {} are:

Example

Use the format() method to insert numbers into strings:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

The format() method takes unlimited number of arguments, and are placed into the respective
placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

You can use index numbers {0} to be sure the arguments are placed in the correct placeholders:

Example
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by double
quotes:

Example

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

You will get an error if you use double quotes inside a string that is surrounded by double quotes:

txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":

Example

The escape character allows you to use double quotes when you normally would not be allowed:

txt = "We are the so-called \"Vikings\" from the north."

Python String Operations

There are many operations that can be performed with strings which makes it one of the most

used data types in Python.

1. Compare Two Strings

We use the == operator to compare two strings. If two strings are equal, the operator returns True.

Otherwise, it returns False. For example,


str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)
Run Code

Output

False
True

In the above example,

• str1 and str2 are not equal. Hence, the result is False.

• str1 and str3 are equal. Hence, the result is True.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

2. Join Two or More Strings

In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"

# using + operator
result = greet + name
print(result)

# Output: Hello, Jack


In the above example, we have used the + operator to join two strings: greet and name.

Iterate Through a Python String

We can iterate through a string using a for loop. For example,


greet = 'Hello'

# iterating through greet string


for letter in greet:
print(letter)

Output

H
e
l
l
o

Python String Length

In Python, we use the len() method to find the length of a string. For example,
greet = 'Hello'

# count length of greet string


print(len(greet))

# Output: 5

String Membership Test

We can test if a substring exists within a string or not, using the keyword in.
print('a' in 'program') # True
print('at' not in 'battle') False

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Methods of Python String

Besides those mentioned above, there are various string methods present in Python. Here are some of

those methods:
Methods Description

upper() converts the string to uppercase

lower() converts the string to lowercase

partition() returns a tuple

replace() replaces substring inside

find() returns the index of first occurrence of substring

rstrip() removes trailing characters

split() splits string from left

startswith() checks if string starts with the specified string

isnumeric() checks numeric characters

index() returns index of substring

Escape Sequences in Python

The escape sequence is used to escape some of the characters present inside a string.

Suppose we need to include both double quote and single quote inside a string,

example = "He said, "What's there?""

print(example) # throws error

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Since strings are represented by single or double quotes, the compiler will treat "He said, " as the

string. Hence, the above code will cause an error.


To solve this issue, we use the escape character \ in Python.
# escape double quotes
example = "He said, \"What's there?\""

# escape single quotes


example = 'He said, "What\'s there?"'

print(example)

# Output: He said, "What's there?"

String Length

String length using len function

To get the length of a string, use the len() function.

The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))
output
13

String length using for loop

def findLen(str):
counter = 0
for i in str:
counter += 1
return counter

str = "Hello"
print(findLen(str))

output
13
String Concatenation

String concatenation means add strings together.

Method 1: String Concatenation using + Operator

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Use the + character to add a variable to another variable:

Example
x = "Python is "
y = "awesome"
z= x+y
print(z)
Example

Merge variable a with variable b into variable c:

a = "Hello"
b = "World"
c=a+b
print(c)
Example

To add a space between them, add a " ":

a = "Hello"
b = "World"
c=a+""+b
print(c)

String Concatenation using format() function

str.format() is one of the string formatting methods in Python, which allows multiple substitutions
and value formatting. It concatenate elements within a string through positional formatting. The
curly braces {} are used to set the position of strings. The first variable stores in the first curly
braces and the second variable stores in the second curly braces. Finally, it prints the value “Hello
World”.

• Python3

var1 = "Hello"

var2 = "World"

# format function is used here to

# combine the string

print("{} {}".format(var1, var2))

# store the result in another variable

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

var3 = "{} {}".format(var1, var2)

print(var3)

Output
Hello World
Hello World

String Concatenation using (, comma)

“,” is a great alternative to string concatenation using “+”. when you want to include single
whitespace. Use a comma when you want to combine data types with single whitespace in between.

var1 = "Hello"
var2 = "World"

# , to combine data types with a single whitespace.


print(var1, var2)

Output
Hello World

Repeat operations on string


we need to repeat the string in the program, and we can do this easily by using the repetition operator
in Python.

The repetition operator is denoted by a '*' symbol and is useful for repeating strings to a certain
length.

Example:

str = 'Python program'


print(str*3)
The above lines of code will display the following outputs:

Python programPython programPython program


Similarly, it is also possible to repeat any part of the string by slicing:

Example:

str = 'Python program'


print(str[7:9]*3) #Repeats the seventh and eighth character three times
prprpr

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Built-in Data Structures

As the name suggests, these Data Structures are built-in with Python which makes programming
easier and helps programmers use them to obtain solutions faster. Let’s discuss each of them in detail.

Lists

Lists are used to store data of different data types in a sequential manner. There are addresses
assigned to every element of the list, which is called as Index. The index value starts from 0 and goes
on until the last element called the positive index. There is also negative indexing which starts from -
1 enabling you to access elements from the last to first. Let us now understand lists better with the
help of an example program.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Creating a list

To create a list, you use the square brackets and add elements into it accordingly. If you do not pass
any elements inside the square brackets, you get an empty list as the output.

my_list = [] #create empty list


print(my_list)
my_list = [1, 2, 3, 'example', 3.132] #creating list with data
print(my_list)

Output:
[]
[1, 2, 3, ‘example’, 3.132]

Adding Elements

Adding the elements in the list can be achieved using the append(), extend() and insert() functions.

• The append() function adds all the elements passed to it as a single element.
• The extend() function adds the elements one-by-one into the list.
• The insert() function adds the element passed to the index value and increase the size of the
list too.

my_list = [1, 2, 3]
1
2print(my_list)
3my_list.append([555, 12]) #add as a single element
4print(my_list)
5my_list.extend([234, 'more_example']) #add as different elements
6print(my_list)
7my_list.insert(1, 'insert_example') #add element i
8print(my_list)

Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]

Deleting Elements

• To delete elements, use the del keyword which is built-in into Python but this does not return
anything back to us.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

• If you want the element back, you use the pop() function which takes the index value.
• To remove an element by its value, you use the remove() function.

Example:

my_list = [1, 2, 3, 'example', 3.132, 10, 30]


del my_list[5] #delete element at index 5
print(my_list)
my_list.remove('example') #remove element with value
print(my_list)
a = my_list.pop(1) #pop element from list
print('Popped Element: ', a, ' List remaining: ', my_list)
my_list.clear() #empty the list
print(my_list)

Output:
[1, 2, 3, ‘example’, 3.132, 30]
[1, 2, 3, 3.132, 30]
Popped Element: 2 List remaining: [1, 3, 3.132, 30]
[]

Accessing Elements

Accessing elements is the same as accessing Strings in Python. You pass the index values and hence
can obtain the values as needed.

my_list = [1, 2, 3, 'example', 3.132, 10, 30]


for element in my_list: #access elements one by one
print(element)
print(my_list) #access all elements
print(my_list[3]) #access index 3 element
print(my_list[0:2]) #access elements from 0 to 1 and exclude 2
print(my_list[::-1]) #access elements in reverse

Output:
1
2
3
example
3.132
10
30
[1, 2, 3, ‘example’, 3.132, 10, 30]

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

example
[1, 2]
[30, 10, 3.132, ‘example’, 3, 2, 1]

Other Functions

You have several other functions that can be used when working with lists.

• The len() function returns to us the length of the list.


• The index() function finds the index value of value passed where it has been encountered the
first time.
• The count() function finds the count of the value passed to it.
• The sorted() and sort() functions do the same thing, that is to sort the values of the list. The
sorted() has a return type whereas the sort() modifies the original list.

my_list = [1, 2, 3, 10, 30, 10]


1
2print(len(my_list)) #find length of list
3print(my_list.index(10)) #find index of element that occurs first
4print(my_list.count(10)) #find count of the element
5print(sorted(my_list)) #print sorted list but not change original
6my_list.sort(reverse=True) #sort original list
7print(my_list)

Output:

6
3
2
[1, 2, 3, 10, 10, 30]
[30, 10, 10, 3, 2, 1]

Mutable Sequence

If the value can change, the object is called mutable, while if the value cannot change, the object is

called immutable. Mutable sequences can be changed after creation. Some of Python’s mutable data

types are: lists, byte arrays, sets, and dictionaries.


List Comprehension

List comprehension offers a shorter syntax when you want to create a new list based on the values of
an existing list.

Example:

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.

Without list comprehension you will have to write a for statement with a conditional test inside:

Example

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


newlist = []

for x in fruits:
if "a" in x:
newlist.append(x)

print(newlist)

output

['apple', 'banana', 'mango']

With list comprehension you can do all that with only one line of code:

example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)
output
['apple', 'banana', 'mango']

The Syntax
newlist = [expression for item in iterable if condition == True]

The return value is a new list, leaving the old list unchanged.

Condition

The condition is like a filter that only accepts the items that valuate to True.

Example

Only accept items that are not "apple":

newlist = [x for x in fruits if x != "apple"]

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

The condition if x != "apple" will return True for all elements other than "apple", making the new list
contain all fruits except "apple".

Example : Even list using list comprehension

list = [i for i in range(11) if i % 2 == 0]

print(list)

Output:
[0, 2, 4, 6, 8, 10]

Example 3: Matrix using List comprehension

matrix = [[j for j in range(3)] for i in range(3)]

print(matrix)

Output:
[[0, 1, 2], [0, 1, 2], [0, 1, 2]]
List Comprehensions vs For Loop
There are various ways to iterate through a list. However, the most common approach is to use
the for loop. Let us look at the below example:

# Empty list

List = []

# Traditional approach of iterating

for character in 'python program':

List.append(character)

# Display list

print(List)

Output:
['p’,’y’,’t’,’h’,’o’,’n’,’p’,’r’,’o’,’g’,’r’,’a’,’m’]
Above is the implementation of the traditional approach to iterate through a list, string, tuple, etc.
Now list comprehension does the same task and also makes the program more simple.
List Comprehensions translate the traditional iteration approach using for loop into a simple
formula hence making them easy to use. Below is the approach to iterate through a list, string,
tuple, etc. using list comprehension.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

# Using list comprehension to iterate through loop

List = [character for character in 'python program']

# Displaying list

print(List)

Output:
['p’,’y’,’t’,’h’,’o’,’n’,’p’,’r’,’o’,’g’,’r’,’a’,’m’]

Dictionary

Dictionaries are used to store key-value pairs. To understand better, think of a phone directory where
hundreds and thousands of names and their corresponding numbers have been added. Now the
constant values here are Name and the Phone Numbers which are called as the keys. And the various
names and phone numbers are the values that have been fed to the keys. If you access the values of
the keys, you will obtain all the names and phone numbers. So that is what a key-value pair is. And in
Python, this structure is stored using Dictionaries. Let us understand this better with an example
program.

Creating a Dictionary

Dictionaries can be created using the flower braces or using the dict() function. You need to add the
key-value pairs whenever you work with dictionaries.

my_dict = {} #empty dictionary


print(my_dict)
my_dict = {1: 'Python', 2: 'Java'} #dictionary with elements
print(my_dict)

Output:
{}
{1: ‘Python’, 2: ‘Java’}

Changing and Adding key, value pairs

To change the values of the dictionary, you need to do that using the keys. So, you firstly access the
key and then change the value accordingly. To add values, you simply just add another key-value pair
as shown below.

my_dict = {'First': 'Python', 'Second': 'Java'}


print(my_dict)
my_dict['Second'] = 'C++' #changing element
print(my_dict)

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

my_dict['Third'] = 'Ruby' #adding key-value pair


print(my_dict)

Output:
{‘First’: ‘Python’, ‘Second’: ‘Java’}
{‘First’: ‘Python’, ‘Second’: ‘C++’}
{‘First’: ‘Python’, ‘Second’: ‘C++’, ‘Third’: ‘Ruby’}

Deleting key, value pairs

• To delete the values, you use the pop() function which returns the value that has been deleted.
• To retrieve the key-value pair, you use the popitem() function which returns a tuple of the key
and value.
• To clear the entire dictionary, you use the clear() function.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}


a = my_dict.pop('Third') #pop element
print('Value:', a)
print('Dictionary:', my_dict)
b = my_dict.popitem() #pop the key-value pair
print('Key, value pair:', b)
print('Dictionary', my_dict)
my_dict.clear() #empty dictionary
print('n', my_dict)

Output:

Value: Ruby
Dictionary: {‘First’: ‘Python’, ‘Second’: ‘Java’}

Key, value pair: (‘Second’, ‘Java’)


Dictionary {‘First’: ‘Python’}

{}

Accessing Elements

You can access elements using the keys only. You can use either the get() function or just pass the
key values and you will be retrieving the values.

my_dict = {'First': 'Python', 'Second': 'Java'}


print(my_dict['First']) #access elements using keys
print(my_dict.get('Second'))

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Output:
Python
Java

Other Functions

You have different functions which return to us the keys or the values of the key-value pair
accordingly to the keys(), values(), items() functions accordingly.

my_dict = {'First': 'Python', 'Second': 'Java', 'Third': 'Ruby'}


print(my_dict.keys()) #get keys
print(my_dict.values()) #get values
print(my_dict.items()) #get key-value pairs
print(my_dict.get('First'))

Output:
dict_keys([‘First’, ‘Second’, ‘Third’])
dict_values([‘Python’, ‘Java’, ‘Ruby’])
dict_items([(‘First’, ‘Python’), (‘Second’, ‘Java’), (‘Third’, ‘Ruby’)])
Python

Tuple

Tuples are the same as lists are with the exception that the data once entered into the tuple cannot be
changed no matter what. The only exception is when the data inside the tuple is mutable, only then the
tuple data can be changed. The example program will help you understand better.

Creating a Tuple

You create a tuple using parenthesis or using the tuple() function.

my_tuple = (1, 2, 3) #create tuple


print(my_tuple)

Output:
(1, 2, 3)

Accessing Elements

Accessing elements is the same as it is for accessing values in lists.

my_tuple2 = (1, 2, 3, 'edureka') #access elements


for x in my_tuple2:
print(x)
print(my_tuple2)

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

print(my_tuple2[0])
print(my_tuple2[:])
print(my_tuple2[3][4])

Output:
1
2
3
edureka
(1, 2, 3, ‘edureka’)
1
(1, 2, 3, ‘edureka’)
e

Appending Elements

To append the values, you use the ‘+’ operator which will take another tuple to be appended to it.

my_tuple = (1, 2, 3)
my_tuple = my_tuple + (4, 5, 6) #add elements
print(my_tuple)

Output:
(1, 2, 3, 4, 5, 6)

Other Functions

These functions are the same as they are for lists.

my_tuple = (1, 2, 3, ['hindi', 'python'])


my_tuple[3][0] = 'english'
print(my_tuple)
print(my_tuple.count(2))
print(my_tuple.index(['english', 'python']))

Output:
(1, 2, 3, [‘english’, ‘python’])
1
3

Set
Sets are used to store multiple items in a single variable.

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

Set is one of 4 built-in data types in Python used to store collections of data, the other 3
are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

* Note: Set items are unchangeable, but you can remove items and add new items.

Sets are written with curly brackets.

Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)
output
{'banana', 'cherry', 'apple'}

Note: Sets are unordered, so you cannot be sure in which order the items will appear.

Set Items

Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered

Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be referred to by index
or key.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items after the set has been created.

Once a set is created, you cannot change its items, but you can remove items and add new items.

Duplicates Not Allowed

Sets cannot have two items with the same value.

Example

Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
output

Downloaded by Harshini S (harshini1165@gmail.com)


lOMoARcPSD|20730777

{'banana', 'cherry', 'apple'}

Get the Length of a Set

To determine how many items a set has, use the len() function.

Example

Get the number of items in a set:

thisset = {"apple", "banana", "cherry"}

print(len(thisset))
output
3
Set Items - Data Types

Set items can be of any data type:

Example

String, int and boolean data types:

set1 = {"apple", "banana", "cherry"}


set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set can contain different data types:

Example
A set with strings, integers and boolean values:
set1 = {"abc", 34, True, 40, "male"}
type(set1)
output
set

From Python's perspective, sets are defined as objects with the data type 'set':

<class 'set'>
Example
What is the data type of a set?
myset = {"apple", "banana", "cherry"}
print(type(myset))

output

<class 'set'>

Downloaded by Harshini S (harshini1165@gmail.com)

You might also like