0% found this document useful (0 votes)
24 views41 pages

Cs 11 Part 2

The document provides an overview of nested loops, strings, and lists in Python. It explains concepts such as string immutability, indexing, slicing, and various string operations, as well as list creation, indexing, and operations like concatenation and repetition. Additionally, it covers built-in string methods and demonstrates how to manipulate strings and lists effectively.

Uploaded by

sharonanlee
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)
24 views41 pages

Cs 11 Part 2

The document provides an overview of nested loops, strings, and lists in Python. It explains concepts such as string immutability, indexing, slicing, and various string operations, as well as list creation, indexing, and operations like concatenation and repetition. Additionally, it covers built-in string methods and demonstrates how to manipulate strings and lists effectively.

Uploaded by

sharonanlee
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/ 41

Nested loops

Nested loops refers to a loop within a loop.


Example: Generating a pattern
n = int(input("Enter the number of rows: "))
for i in range(n):
for j in range(i+1):
print("*", end="")
print()

Output
Enter the number of rows: 5
*
**
***
****
*****

String
String: String is a sequence of UNICODE characters. A string can be created by enclosing one or more
characters in single, double or triple quotes (' ' or '' '' or ''' ''').
Example
>>> str1 = 'Python'
>>> str2 = "Python"
>>> str3 = '''Multi Line
String'''
>>> str4 = """Multi Line
String"""

Terminology

Whitespace Characters: Those characters in a string that represent horizontal or vertical space.
Example: space (' '), tab ('\t'), and newline ('\n')

75
Indexing in Strings
● Indexing is used to access individual characters in a string using a numeric value.
● The index of the first character (from left) in the string is 0 and the last character is n-1
● The index can also be an expression including variables and operators but the expression must
evaluate to an integer
● Forward indexing, also known as positive indexing, starts from left to right, with the first character
having index 0, second character having index 1, and so on.
● Backward indexing, also known as negative indexing, starts from right to left, with the last character
having index -1, second-last character having index -2, and so on

Example
>>> str1 = 'Python' >>> str1 = 'Python'
>>> str1[0] >>> str1[2+3]
'P' 'n'

Slicing
Slicing is the process of extracting a substring from a given string. It is done using the operator ':'.
Syntax : string[start:end:step].
start : 'start' is the starting index of the substring (inclusive).
end : 'end' is the ending index of the substring (exclusive)
step : 'step' is the difference between the index of two consecutive elements. Default value is 1
Case-1 Case-2 Case-3 Case-4
print(str1[:3]) print(str1[1:4]) print(str1[0:5:2]) print(str1[-5:-1])

Output Output Output Output


PYT YTH PTO YTHO
Case-5 Case-6 Case-7
print(str1[-1:-4]) print(str1[:-5:- print(str1[:-5])
1])
Output Output
'' Output P
NOHT

76
Mutable Object
If the value of an object can be changed after it is created, It is called mutable object
Example
Lists, Set and dictionaries.

Immutable Object
If the value of an object cannot be changed after it is created, it is called immutable object
Example
Numeric, String and Tuple

String is Immutable
A string is an immutable data type. It means that the value (content) of a string object cannot be changed
after it has been created. An attempt to do this would lead to an error.
Example
>>> str1 = 'Python'
>>> str1[1]='Y'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

Traversal of a String
Accessing the individual characters of string i.e. from first
1. Using only for Loop
str1 = 'Computer'
for ch in str1:
print(ch, end=' ')

2. Using For Loop and range function


str1 = 'Computer'
for ch in range(0,len(str1)):
print(str1[ch],end=' ')

3. Using while Loop


str1 = 'Computer'
i = 0
while i < len(str1):
print(str1[i],end = ' ')
i+= 1

77
String Operations
We can perform various operations on string such as concatenation, repetition, membership and slicing.

Concatenation
Operator : +
>>> str1 = "Python"
>>> str2 = "Programming"
>>> str1 + str2
'PythonProgramming'

Repetition
Use : To repeat the given string multiple times.
Repetition operator : *
>>> str1 = "Hello "
>>> str1*5
'Hello Hello Hello Hello Hello'

Membership
Membership is the process of checking whether a particular character or substring is present in a sequence
or not. It is done using the 'in' and 'not in' operators.
Example
>>> str1 = "Programming in Python"
>>> "Prog" in >>> "ming in" >>> "Pyth " in >>> "Pyth "
str1 in str1 str1 not in str1
True True False True

String Methods/Functions

Python has several built-in functions that allow us to work with strings

78
len() capitalize()
Returns the length of the given string converts the first character of a string to capital
>>> str1 = 'Hello World!' (uppercase) letter and rest in lowercase.
>>> len(str1) str1 = "python Programming for
12 11th"
str1.capitalize()
'Python programming for 11th'
title() lower()
converts the first letter of every word in the string Returns the string with all uppercase letters
in uppercase and rest in lowercase converted to lowercase
>>> str1 = "python ProGramming >>> str1 = "PYTHON PROGRAMMING for
for 11th" 11th"
>>> str1.title() >>> str1.lower()
'Python Programming For 11Th' 'python programming for 11th'

upper() count()
Returns the string with all lowercase letters Returns number of times a substring occurs in the
converted to uppercase given string
>>> str1 = "python programming >>> str1 = "python programming for
for 11th" 11th"
>>> str1.upper() >>> str1.count("p")
'PYTHON PROGRAMMING FOR 11TH' 2
>>> str1.count("pyth")
1

find() index()
Returns the index of the first occurrence of Same as find() but raises an exception if the
substring in the given string. If the substring is substring is not present in the given string
not found, it returns -1 >>> str1 = "python programming for
>>> str1 = "python programming 11th"
for 11th" >>> str1.index('r')
>>> str1.find('r') 8
8 >>> str1.index('u')
>>> str1.find('u') Traceback (most recent call last):
-1 File "<stdin>", line 1, in
<module>
ValueError: substring not found

79
isalnum() isalpha()
The isalnum() method returns True if all Returns True if all characters in the string are
characters in the string are alphanumeric (either alphabets, Otherwise, It returns False
alphabets or numbers). If not, it returns False. >>> 'Python'.isalpha()
>>> str1 = 'HelloWorld' True
>>> str1.isalnum() >>> 'Python 123'.isalpha()
True False
>>> str1 = 'HelloWorld2'
>>> str1.isalnum()
True

isdigit() isspace()
returns True if all characters in the string are Returns True if has characters and all of them are
digits, Otherwise, It returns False white spaces (blank, tab, newline)
>>> '1234'.isdigit() >>> str1 = ' \n \t'
True >>> str1.isspace()
>>> '123 567'.isdigit() True
False >>> str1 = 'Hello \n'
>>> str1.isspace()
False

islower() isupper()
returns True if the string has letters all of them returns True if the string has letters all of them are
are in lower case and otherwise False. in upper case and otherwise False.
>>> str1 = 'hello world!' >>> str1 = 'HELLO WORLD!'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello 1234' >>> str1 = 'HELLO 1234'
>>> str1.islower() >>> str1.isupper()
True True
>>> str1 = 'hello ??' >>> str1 = 'HELLO ??'
>>> str1.islower() >>> str1.isupper()
True True

80
strip() lstrip()
Returns the string after removing the whitespaces Returns the string after removing the whitespaces
both on the left and the right of the string only on the left of the string
>>> str1 = ' Hello World! ' >>> str1 = ' Hello World! '
>>> str1.strip() >>> str1.lstrip()
'Hello World!' 'Hello World! '

rstrip() replace(oldstr,newstr)
Returns the string after removing the whitespaces used to replace a particular substring in a string
only on the right of the string with another substring
>>> str1 = ' Hello World! ' >>> str1 = 'Hello World!'
>>> str1.rstrip() >>> str1.replace('o','*')
' Hello World!' 'Hell* W*rld!'
partition() split()
The partition() function is used to split a string Returns a list of words delimited by the specified
into three parts based on a specified separator. substring. If no delimiter is given then words are
>>> str1 = 'India is a Great Country' separated by space.
>>> str1.partition('is') >>> str1 = 'India is a Great Country'
('India ', 'is', ' a Great Country') >>> str1.split()
>>> str1.partition('are') ['India','is','a','Great', 'Country']
('India is a Great Country',' ',' ') >>> str1 = 'India is a Great Country'
>>> str1.split('a')
['Indi', ' is ', ' Gre', 't Country']

81
startswith() join()
startswith() function is used to check whether a str.join(sequence)
given string starts with a particular substring. returns a string in which the string elements of
sequence have been joined by str separator. if few
endswith() of the members of the sequence are not string, error
endswith() function is used to check whether a is generated.
given string ends with a particular substring. >>> '*-*'.join('Python')
'P*-*y*-*t*-*h*-*o*-*n'
str = "Python Programming >>> '*-
Language" *'.join(['Ajay','Abhay','Alok'])
print(str.startswith("Pyt")) 'Ajay*-*Abhay*-*Alok'
print(str.startswith("Pyth")) >>> '*-
print(str.endswith("age")) *'.join(['Ajay','Abhay',123])
print(str.endswith("uage")) Traceback (most recent call last):
print(str.startswith("Pyts")) File "<stdin>", line 1, in
<module>
Output TypeError: sequence item 2:
True expected str instance, int found
True
True
True
False

82
LIST IN PYTHON
● List is a sequence i.e. sequenced data type.
● List can store multiple values in a single object.
● List is an ordered sequence of values/elements.
● Elements of a list are enclosed in square brackets [ ], separated by commas.
● List are mutable i.e. values in the list can be modified.
● The elements in a list can be of any type such as integer, float, string, objects etc.
● List is heterogeneous type i.e. collection of different types.
L = [5, 8, 6, 1, 9]

Length = 5 (Number of elements)

What is a sequence?
Sequence is a positional ordered collection of items, which can be accessed using index. Examples of
sequence are List, Tuple, String etc.

List is Mutable
In Python, lists are mutable. It means that the contents of the list can be changed after it has been created.

>>> L = [1, 5, 7, 2]

>>> L

[1, 5, 7, 2]

Change the second element of list from 5 to 8

>>> L[1]=8

>>> L

[1, 8, 7, 2]

90
How to create a list in Python:
Using integer values

>>> L = [1, 5, 7, 2]

>>> L

[1, 5, 7, 2]

Using heterogeneous type:

>>> L = [1.5, 2, "Hello", 'S']

>>> L

[1.5, 2, "Hello", 'S']

Using list( ) function:


list ( ) function is useful to create or convert any iterable into list. For example, create a list from string.

>>> L=list("Hello")

>>> L

['H', 'e', 'l', 'l', 'o']

Creating Empty List:

>>> L=[ ]

>>> L

[]

Creating empty list using list( )

>>> L=list( )

>>> L

[]

91
Indexing in List:
● Index means the position of an item in an iterable type.
● Indexing can be positive or negative.
● Positive Indexes start from 0 and are positioned like 0, 1, 2, ….
● The index of the first element is always 0 and the last element is n-1 where n is the total number of
elements in the list.
● Negative index starts from the last element and is labeled as -1, -2, -3, ……

For example:

Accessing elements using index:


Syntax
Object_name[Index]
For Ex:

>>> L = [5, 8, 6, 1, 9]

>>> L[0]

>>> L[3]

>>> L[-1]

>>> L[-4]

>>> L[5]

IndexError: list index out of range

92
>>> L[-6]

IndexError: list index out of range

If we try to access the element from outside the index range then the interpreter raises an IndexError.

LIST OPERATIONS
Slicing in List:
Note: Slicing never gives IndexError
Syntax:
Object_name[start : stop : interval]
● Here start, stop and interval all have default values.
● Default value of start is 0, stop is n (if interval is +ive) and -1 if interval is –ive
● Default value interval is 1
● In slicing, start is included and stop is excluded.
● If interval is +ive then slicing is performed from left to right. For Ex:

>>> L[1:4:1]

[8, 6, 1]

If we give an index out of range then it is considered as the default value.

>>> L[1:5:2]

[8, 1]

Start index is not given then it consider as default value

>>> L[:5:2]

[5, 6, 9]

Start, stop and interval is not given then they consider as default value

93
>>> L[: :]

[5, 8, 6, 1, 9]

If start>=stop and interval is positive the slicing will return empty list

>>> L[4:2]

[]

>>> L[4:4]

[]

>>> L[4:2:1]

[]

If the interval is negative then slicing is performed from right to left. For Ex:

Access the list element where start index is 4 and stop index is 1 in reverse order
>>>L[4:1:-1]
[9, 1, 6]

Access the list element where start index is 5 and stop index is 0 with interval 2 in reverse order
>>>L[5:0:-2]
[9, 6]

>>>L[-1:-4:-1]
[9, 1, 6]

>>>L[-1:-4:-1]
[9, 1, 6]

Access the list in reverse order


>>>L[: : -1]
[9, 1, 6, 8, 5]

94
>>> L[-1:2:-1]
[9, 1]

Concatenation of two lists:


Concatenation is the process of joining the elements of a particular list at the end of another list
>>> L1=[1,2,3]
>>> L2=['a','b','c']

Using concatenation operator (+)


>>> L1+L2
[1, 2, 3, 'a', 'b', 'c']

Repetition Operator
● The repetition operator makes multiple copies of a list and joins them all together. The general format
is: list * n,
where ‘list’ is a list and n is the number of copies to make.
>>> L=[0]*3
>>> L
[0, 0, 0]
In this example, [0] is a list with one element 0, The repetition operator makes 3 copies of this list and joins
them all together into a single list.

>>> L = [1, 2, 3]*3


>>> L
[1, 2, 3, 1, 2, 3, 1, 2, 3]
In this example, [1, 2, 3] is a list with three elements 1, 2 and 3. The repetition operator makes 3 copies of
this list and joins them all together into a single list.

Membership operator
Membership operator is used to check or validate the membership of an element in the list or sequence.
There are two types of membership operators
1. in operator: It return True if a element with the specified value is present in the List
2. not in operator: It return True if a element with the specified value is not present in the List

95
Examples:
L = [5,"India", 8, 6, 1]
>>> 5 in L
True

>>> "India" in L
True

>>> 9 in L
False

>>> 9 not in L
True

Traversing a list using loops


Traversing a list means to visit every element of the list one by one. One of the most common methods to
traverse a Python list is to use a for loop.
Ex: Write a program in Python to traverse a list using for loop.
L = [5, 8, 9, 6, 1]
for i in L:
print(i)
Output:
5
8
9
6
1

Using range() method:


We can traverse a list using range() method
L = [5, 8, 9, 6, 1]
n = len(L)
for i in range(n):
print(L[i])
Output:
5
8
9

96
6
1

Built-in functions/methods of list:


1: len():
It returns the total number of elements in the list i.e. length of the list.
For ex:
>>> L = [8, 6, 3, 9, 1]
>>> len(L)
5
It returns the total numbers of elements in the list i.e. 5

2: list()
list() is a function used to convert an iterable into a list.
For Ex:
>>> S="Python"
>>> L=list(S)
>>> L
['P', 'y', 't', 'h', 'o', 'n']
In the above example, a string S is converted into the List.

3: append()
appends an element at the end of the list.
list.append(item)
append() adds a single element to the end of a list.
The length of the list increases by one.
The method doesn’t return any value
>>> L = [4,5,9,2,6]
>>> L.append(1)
>>> L
[4, 5, 9, 2, 6, 1]

A list is an object. If we append another list onto a list, the parameter list will be a single object at the end
of the list.
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> L1.append(L2)
>>> L1
[1, 2, 3, [4, 5, 6]]

97
4: extend()
extend() is a method of list, which is used to merge two lists.
extend() iterates over its argument and adds each element at the end of the list.
list.extend(iterable)
Argument of extend() method is any iterable (list, string, set, tuple etc.)
The length of the list increases by a number of elements in its argument.
The method doesn’t return any value
>>> L1=[1,2,3]
>>> L2=[4,5,6]
>>> L1.extend(L2)
>>> L1
[1, 2, 3, 4, 5, 6]
A string is iterable, so if you extend a list with a string, you’ll append each character as you iterate over
the string.
>>> L1=[1,2,3]
>>> S="Python"
>>> L1.extend(S)
>>> L1
[1, 2, 3, 'P', 'y', 't', 'h', 'o', 'n']

5: insert()
append() and extend() method is used to add an element and elements of an iterable object respectively at
the end of the list. If we want to add an element at any index then we can use insert() method of list.
Syntax: list_name.insert(index, element)
>>> L=[1,2,3]
Insert element 8 at index 1 i.e. at 2nd position
>>> L.insert(1,8)
>>> L
[1, 8, 2, 3]

6: count()
count() method returns how many times a given element occurs in a List i.e. it returns the frequency of an
element in the list.
Syntax: list_name.count(element)
>>> L = [1, 2, 8, 9, 2, 6, 2]
>>> L
[1, 2, 8, 9, 2, 6, 2]
>>> L.count(2)
3

98
7: index()
index() is a method of the list, which returns the index of the first occurrence of the element.
Syntax: list_name.index(element, start, end)
element – The element whose index for first occurrence is to be returned.
start (Optional) – The index from where the search begins. Start is included.
end (Optional) – The index from where the search ends. End is excluded.
>>> L = [5, 8, 9, 6, 1, 8]
>>> L.index(8)
1
>>> L.index(8,2)
5
>>> L.index(8,2,6)
5
>>> L.index(8,2,5)
ValueError: 8 is not in list
>>> L.index(8,2,7)
5

8: remove()
remove() method of list is used to delete the first occurrence of the given element. If the given element is
not exist in the list then it will give the ValueError
Syntax: list_name.remove(element)
>>> L
[5, 8, 9, 6, 1, 8]
>>> L.remove(8)
>>> L
[5, 9, 6, 1, 8]
>>> L.remove(4)
ValueError: list.remove(x): x not in list

9: pop()
Syntax: list_name.pop(index)
Index is optional. If index is not given, pop() method of list is used to remove and return the last element
of the list, otherwise remove and return the element of the given index. If Index is out of range then it
gives IndexError.
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
#remove the last element from the list
>>> L.pop()

99
1
>>> L
[5, 8, 9, 6]
#remove the element from the list whose index is 1
>>> L.pop(1)
8
>>> L
[5, 9, 6]
>>> L.pop(4)
IndexError: pop index out of range

10: reverse()
reverse() method of the list used to reverse the order of the elements of the list
Syntax: list_name.reverse()
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
>>> L.reverse()
>>> L
[1, 6, 9, 8, 5]

11: sort()
sort() method can be used to sort List in ascending, descending, or user-defined order. It sort the existing
list.
Syntax: List_name.sort(reverse=True/False)
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
#sort the elements of the list in ascending order
>>> L.sort()
>>> L
[1, 5, 6, 8, 9]
#sort the elements of the list in descending order
>>> L.sort(reverse=True)
>>> L
[9, 8, 6, 5, 1]

12: sorted()
sorted() is a function of list. sorted() function returns a sorted list in ascending order by default. It does not
sort or change the existing list.

100
>>> L = [5, 8, 9, 6, 1]
>>> L
[5, 8, 9, 6, 1]
>>> sorted(L)
[1, 5, 6, 8, 9]
>>> L
[5, 8, 9, 6, 1]
#Create a list which contains the element of another list in descending order.
>>> L1=sorted(L, reverse=True)
>>> L1
[9, 8, 6, 5, 1]

13: min()
min() function of the list is used to find the minimum element from the list.
>>> L = [5, 8, 1, 6, 9]
>>> min(L)
1
# If the elements of the list are string then min() returns the minimum element based on the ASCII values.
>>> L=['a','D','c']
>>> min(L)
'D'

14: max()
max() function of the list is used to find the maximum element from the list.
>>> L = [5, 8, 1, 6, 9]
>>> max(L)
9
# If the elements of the list are string then max() returns the maximum element based on the ASCII
values.
>>> L=['a','D','c']
>>> max(L)
'c'

15: sum()
sum() is a function of list, which returns the sum of all elements of the list.
>>> L = [5, 8, 9, 6, 1]
>>> sum(L)
29

101
Nested List:
A list within another list is called the nested list i.e. list of list.

>>> L = [1, [2, 3, 4], 'Python', 3.5]


>>> L[1]
[2, 3, 4]
>>> L[1][0]
2
>>> L[2]
'Python'
>>> L[2][2]
't'

Suggested Programs:
Program-1 : Write a program in Python to find the maximum and minimum number from the
given List.

L=[]
c='y'
while c=='y' or c=='Y':
a=int(input("Enter an integer number to append in the list: "))
L.append(a)
c=input("Do you want to add more elements in the list (Y/N): ")
print("List is: \n", L)
print("Minimum(Smallest) number of the list = ",min(L))
print("Maximum(Largest) number of the list = ",max(L))

Output:
Enter an integer number to append in the list: 5
Do you want to add more elements in the list (Y/N): Y
Enter an integer number to append in the list: 8
Do you want to add more elements in the list (Y/N): Y

102
Enter an integer number to append in the list: 1
Do you want to add more elements in the list (Y/N): Y
Enter an integer number to append in the list: 9
Do you want to add more elements in the list (Y/N): Y
Enter an integer number to append in the list: 6
Do you want to add more elements in the list (Y/N): N
List is:
[5, 8, 1, 9, 6]
Minimum (Smallest) number of the list = 1
Maximum (Largest) number of the list = 9

Program-2 : Write a program in Python to find the mean of numeric values stored in the given List.

L=eval(input("Enter a list: "))


print("List is: \n", L)
NL=[ ]
for i in L:
if isinstance(i, (int, float)) ==True:
NL.append(i)
print("Numeric List is: \n", NL)
mean=sum(NL)/len(NL)
print("Mean of the numeric values of the list = ",mean)

Output:
Enter a list: [5, 8, 'hello', (1,2), [7,8], 9.5, 10]
List is:
[5, 8, 'hello', (1, 2), [7, 8], 9.5, 10]
Numeric List is:
[5, 8, 9.5, 10]
Mean of the numeric values of the list = 8.125

Program-3 : Write a program in Python to find the index of the given number from a List using
linear search.

L= [10, 20, 30, 40, 50]


print("List is : ",L)
c='Y'
while c=='Y' or c=='y':
n=int(input("Enter the number to be search in the list: "))
found=False
for i in L:

103
if i==n:
print("Element found at index: ",L.index(i))
found=True
if found==False:
print("Number is not found in the list")
c=input("Do you want to search more item (Y/N): ")
Output:
List is : [10, 20, 30, 40, 50]
Enter the number to be search in the list: 20
Element found at index: 1
Do you want to search more item (Y/N): y
Enter the number to be search in the list: 50
Element found at index: 4
Do you want to search more item (Y/N): y
Enter the number to be search in the list: 15
Number is not found in the list
Do you want to search more item (Y/N): n
Program-4 : Write a program in Python to count the frequency of all elements of a list.

L= [10, 20, 30, 20, 40, 30, 20, 50]


print("List is: ",L)
Uni= []
Freq= []
for i in L:
if i in Uni:
index=Uni.index(i)
Freq[index]+= 1
else:
Uni.append(i)
Freq.append(1)
for i in range(len(Uni)):
print(Uni[i],":",Freq[i])
Output:
List is: [10, 20, 30, 20, 40, 30, 20, 50]
10 : 1
20 : 3
30 : 2
40 : 1
50 : 1

104
------------------------------------------------------------------------------------------------------------------------------
TUPLE IN PYTHON:
● Tuple is a sequence data type.
● Tuple is a heterogamous collection of data.
● Tuple is an immutable data type i.e. it cannot be changed after being created.
● Tuple is denoted by parenthesis i.e. ( ) and the elements of the tuple are comma separated.

How to create a tuple in Python:


#Create a tuple with three integer element
>>> T= (8, 6, 7)
>>> T
(8, 6, 7)
>>> type(T)
<class 'tuple'>

#Create a tuple with a single element. Comma must be used after the element.
>>> T= (5,)
>>> T
(5,)
>>> type(T)
<class 'tuple'>

#Without parenthesis comma separated values are also treated as tuples.


>>> T=5,
>>> T
(5,)

#Without a comma, a single element is not tuple.


>>> T = (5)
>>> T
5
>>> type(T)
<class 'int'>

#Following is string, not tuple


>>> T= ('Hello')

105
>>> T
'Hello'
>>> type(T)
<class 'str'>
>>> T= (5, 9.8,'Hello', 9)
>>> T
(5, 9.8, 'Hello', 9)

#Create a tuple without parentheses.


>>> T=1, 2, 3, 4
>>> T
(1, 2, 3, 4)
>>> type(T)
<class 'tuple'>

Tuple Indexing

>>> T= (5, 8, 6, 1, 9)
>>> T
(5, 8, 6, 1, 9)
>>> T[2]
6
>>> T[-3]
6
>>> T[6]
IndexError: tuple index out of range

106
Tuple Operations
Concatenation
Using + operator
>>> T1=(1,2,3)
>>> T2=(4,5,6)
>>> T=T1+T2
>>> T
(1, 2, 3, 4, 5, 6)

Repetition
Tuple can be created using the repetition operator, *.
The repetition operator makes multiple copies of a tuple and joins them all together. The general format
is: T * n,
Where T is a tuple and n is the number of copies to make.
>>> T= (1, 2)*3
>>> T
(1, 2, 1, 2, 1, 2)
In this example, (1, 2) is a tuple with two elements 1 and 2, The repetition operator makes 3 copies of this
tuple and joins them all together into a single tuple.

Membership
Membership operator is used to check or validate the membership of an element in the tuple or sequence.
There are two types of membership operators
1. in operator: It return True if a element with the specified value is present in the tuple
2. not in operator: It returns True if an element with the specified value is not present in the tuple.
Examples:
T = (5,"India", 8, 6, 1)
>>> 5 in T
True
>>> "India" in T
True
>>> 9 in T
False
>>> 9 not in T
True

107
Slicing in Tuple:
Note: Slicing never give IndexError
Syntax:
Object_name[start : stop : interval]
● Here start, stop and interval all have default values.
● Default value of start is 0, stop is n (if interval is +ive) and -1 if interval is –ive
● Default value interval is 1
● In slicing start is included and stop is excluded.
● If interval is +ive then slicing is performed from left to right. For Ex:

>>> T[1:4:1]
(8, 6, 1)

If we give an index out of range then it is considered as the default value.


>>> T[1:5:2]
(8, 1)

If start index is not given then it consider as default value


>>> T[:5:2]
(5, 6, 9)

If start>=stop and interval is positive the slicing will return empty list
>>> T[4:2]
()

If interval is negative slicing performed from right to left


Access the list element where start index is 4 and stop index is 1 in reverse order
>>>T[4:1:-1]
(9, 1, 6)

Access the list element where start index is 5 and stop index is 0 with interval 2 in reverse order
>>>T[5:0:-2]
(9, 6)

108
>>>T[-1:-4:-1]
(9, 1, 6)
>>>T[-1:-4:-1]
(9, 1, 6)
Built-in functions/methods of tuple:
1: len():
len() is a function of tuple.
It returns the total number of elements in the tuple i.e. length of the tuple.
For ex:
>>> T = (8, 6, 'Hello', 9, 1)
>>> len(T)
5
It returns the total numbers of elements in the tuple i.e. 5

2: tuple()
tuple() is a function used to convert an object into tuple.
For Ex:
>>> S="Python"
>>> T=tuple(S)
>>> T
('P', 'y', 't', 'h', 'o', 'n')
In the above example, a string S is converted into the tuple.

3: count()
count() is a function used to count() the number of occurrences of an element in the tuple.
>>> T = (1, 2, 3, 2, 4, 2, 5)
>>> T.count(2)
3

4: index()
It returns the index of the first occurrence of the element
>>> T = (1, 2, 3, 2, 4, 2, 5)
>>> T.index(2)
1

5: sorted()
It is a built-in function to sort the elements of Tuple.

109
It return a new list of sorted elements of the tuple in ascending order (by default)
It does not change the existing tuple.

T = (1, 2, 3, 2, 4, 2, 5)
print(sorted(T))
Output:
[1, 2, 2, 2, 3, 4, 5]

For sort the elements in descending order use reverse = True


T = (1, 2, 3, 2, 4, 2, 5)
print(sorted(T, reverse=True))
Output:
[5, 4, 3, 2, 2, 2, 1]

6: min()
It is a built-in function of the tuple. It returns the smallest element from the tuple.
T = (5, 8, 3, 9, 6, 4)
print(min(T))
Output:
3

7: max()
It is a built-in function of the tuple. It returns the largest element from the tuple.
T = (5, 8, 3, 9, 6, 4)
print(max(T))
Output:
9

8: sum()
It is a built-in function of the tuple. It returns the sum of all elements of the tuple.
T = (5, 8, 3, 9, 6, 4)
print(sum(T))
Output:
35

Nested Tuple
A nested tuple is a tuple that has been placed inside of another tuple.
>>> T = (5, (8, 6, 4), 3, 9)

110
>>> T
(5, (8, 6, 4), 3, 9)
>>> T[1]
(8, 6, 4)
>>> T[1][1]
6

A list can be an element of a tuple.


>>> T = (5, [8, 6, 4], 3, 9)
>>> T
(5, [8, 6, 4], 3, 9)

>>> T[1][2]
4
List is a mutable type. So we can change the value of the list, even if it is nested inside the tuple.

>>> T[1][2]=7
>>> T
(5, [8, 6, 7], 3, 9)

Suggested Programs:
Program-1 : Write a program in Python to find the maximum and minimum number from the given
tuple.
T= (5, 8, 9, 6, 2, 5)
print("Tuple is: \n", T)
print("Minimum(Smallest) number of the Tuple = ",min(T))
print("Maximum(Largest) number of the Tuple = ",max(T))

Output:
Tuple is:
(5, 8, 9, 6, 2, 5)
Minimum(Smallest) number of the Tuple = 2
Maximum(Largest) number of the Tuple = 9

Program-2 : Write a program in Python to find the mean of numeric values stored in the given
tuple.

111
T=eval(input("Enter a numeric tuple: "))
print("Tuple is: \n", T)
mean=sum(T)/len(T)
print("Mean of the numeric values of the tuple = ",mean)

Output:
Enter a numeric tuple: (2, 8, 9, 6, 5)
Tuple is:
(2, 8, 9, 6, 5)
Mean of the numeric values of the tuple = 6.0

Program-3 : Write a program in Python to find the index of the given number from a tuple using
linear search.

T= (5, 8, 9, 2, 6)
print("Tuple is : ",T)
c='Y'
while c=='Y' or c=='y':
n=int(input("Enter the number to be search in the tuple: "))
found=False
for i in T:
if i==n:
print("Element found at index: ",T.index(i))
found=True
if found==False:
print("Number is not found in the list")
c=input("Do you want to search more item (Y/N): ")

Output:
Tuple is : (5, 8, 9, 2, 6)
Enter the number to be search in the tuple: 8
Element found at index: 1
Do you want to search more item (Y/N): y
Enter the number to be search in the tuple: 2
Element found at index: 3
Do you want to search more item (Y/N): n

112
Program-4 : Write a program in Python to count the frequency of all elements of a tuple.

T= (10, 20, 30, 20, 40, 30, 20, 50)


print("Tuple is: ",T)
Uni= ()
for i in T:
if i not in Uni:
Uni = Uni + (i,)
for i in Uni:
print(i,":",T.count(i))

Output:
Tuple is: (10, 20, 30, 20, 40, 30, 20, 50)
10 : 1
20 : 3
30 : 2
40 : 1
50 : 1
-----------------------------------------------------------------------------------------------------------------------------

113
DICTIONARY IN PYTHON
Introduction to Dictionary:
• Dictionary is a sequence data type.
• Dictionary is a mutable data type i.e. it can be changed after being created.
• Dictionary is denoted by curly braces i.e. {}
• Dictionaries are used to store data values in key : value pairs
• Keys of the dictionary are unique.

>>> D = {1:10, 2:20, 3:30}


>>> D
{1: 10, 2: 20, 3: 30}

Accessing items in a dictionary using keys:


>>> D = {1:10, 2:20, 3:30}
>>> D
{1: 10, 2: 20, 3: 30}

We can access the values of any key from the dictionary using following syntax:
Dict_Name[key_name]
>>> D[1]
10
>>> D[2]
20
>>> D[3]
30

If the key is duplicated at the time of dictionary creation then the value assigned at the last will be stored in
the key.
>>> D = {1:10, 2:20, 3:30, 1:40, 4:50}
>>> D
{1: 40, 2: 20, 3: 30, 4: 50}
>>> D = {'A':10,'B':20,'C':30}
>>> D.get('A')
10
Mutability of a dictionary:
Mutability means the values of a key can be updated in the dictionary.
Dict_Name[Key_Name] = New_Value

114
>>> D = {'A':10,'B':20,'C':30}
Change the value of key ‘A’ from 10 to 15.
>>> D['A']=15
>>> D
{'A': 15, 'B': 20, 'C': 30}

Adding a new item in dictionary:


Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Dict_Name[New_Key_Name] = Value
>>> D = {1:10, 2:20, 3:30}
>>> D
{1: 10, 2: 20, 3: 30}
>>> D[4]=40
>>> D
{1: 10, 2: 20, 3: 30, 4: 40}

Traversing a dictionary
• You can loop through a dictionary by using for loop.
• When looping through a dictionary, the return values are the keys of the dictionary, but there are
methods to return the values as well.
We can use following methods to traversing a dictionary:

keys()
It returns the keys of the dictionary, as a list.

>>> D = {1:10, 2:20, 3:30}


>>> D.keys()
dict_keys([1, 2, 3])
#Print the keys of the dictionary.
D = {1:10, 2:20, 3:30}
for i in D.keys():
print(i)
Output:
1
2
3

values()
It returns the values of the dictionary, as a list.

>>> D = {1:10, 2:20, 3:30}


>>> D.values()

115
dict_values([10, 20, 30])

#Print the values of the dictionary.


D = {1:10, 2:20, 3:30}
for i in D.values():
print(i)

Output:
10
20
30

items()
It returns the key-value pairs of the dictionary, as tuples in a list.

>>> D = {1:10, 2:20, 3:30}


>>> D.values()
dict_items([(1, 10), (2, 20), (3, 30)])

#Print all keys and values of the dictionary.


D = {1:10, 2:20, 3:30}
for i in D.items():
print(i)

Output:
(1, 10)
(2, 20)
(3, 30)

Built-in functions/methods of dictionary:


1. len()
It returns the number of keys in the list.

>>> D = {1:10, 2:20, 3:30}


>>> len(D)
3

2. dict()
The dict() function is used to create a dictionary.
>>> D = dict(name = "Shiva", age = 26, country = "India")
>>> D
{'name': 'Shiva', 'age': 26, 'country': 'India'}

116
3. get()
The get() method returns the value of the specified key.

>>> D = {1:10, 2:20, 3:30}


#Return the value of key ‘1’
>>> D.get(1)
10
#Returns the value of key ‘3’
>>> D.get(3)
30

4. update()
The update() method inserts specified elements to the dictionary or merge two dictionaries.
dictionary.update(iterable)

>>> D = {1:10, 2:20, 3:30}


>>> D.update({4:40})
>>> D
{1: 10, 2: 20, 3: 30, 4: 40}

If key is already exist in the dictionary then the value of the existing key will be update:

>>> D.update({3:35})
>>> D
{1: 10, 2: 20, 3: 35, 4: 40}

Merge two dictionaries using update() method


>>> D1={1:10,2:20}
>>> D1
{1: 10, 2: 20}
>>> D2={3:30,4:45}
>>> D2
{3: 30, 4: 45}
>>> D1.update(D2)
>>> D1
{1: 10, 2: 20, 3: 30, 4: 45}

5. del
del is a keyword.
del is used to delete an element from the dictionary using keyname.

>>> D = {1:10, 2:20, 3:30}


>>> D

117
{1: 10, 2: 20, 3: 30}
>>> del D[1]
>>> D
{2: 20, 3: 30}

del can also be used to delete the complete dictionary

>>> del D
>>> D
NameError: name 'D' is not defined.

6. clear()
The clear( ) method is used to delete all the elements (key:value pairs) from a dictionary.
It does not delete the structure of the dictionary

>>> D = {1:10, 2:20, 3:30}


>>> D
{1: 10, 2: 20, 3: 30}
>>> D.clear()
>>> D
{}

7. pop()
pop() method is used to delete a specific element from the dictionary and also return the value of the deleted
element.

>>> D = {1:10, 2:20, 3:30}


>>> D
{1: 10, 2: 20, 3: 30}
>>> D.pop(2)
20
>>> D
{1: 10, 3: 30}

8. popitem()
popitem() method is used to delete the last element from the dictionary. It return the (key, value) pair of
deleted elements in tuple type.

>>> D = {1:10, 2:20, 3:30}


>>> D
{1: 10, 2: 20, 3: 30}
>>> D.popitem()
(3, 30)

118
9. setdefault()

setdefault() method returns the value of the specified key. If the key does not exist in the dictionary it insert
the key into dictionary, with the specified value

>>> D = {1:10, 2:20, 3:30}


Return the value of key ‘2’
>>> D.setdefault(2)
20

Return the value of key ‘3’. If key is already exists in the dictionary, 2nd argument does not effects

>>> D.setdefault(3,50)
30
>>> D
{1: 10, 2: 20, 3: 30}

Return the value of key ‘4’. If the key is not found in the dictionary, then add the key and specified value
and then return the value of the key.

>>> D.setdefault(4,40)
40
>>> D
{1: 10, 2: 20, 3: 30, 4: 40}

If the key is not found in the dictionary, then add the key and None as the value of key (if value is not passed
in the argument). It will not return anything.

>>> D.setdefault(5)
>>> D
{1: 10, 2: 20, 3: 30, 4: 40, 5: None}

10. max()
max() function returns the largest key from the dictionary. Comparison done on the bases of ASCII values

>>> D={1: 10, 2: 20, 3: 30, 4: 40}


>>> max(D)
4

If keys are string, here ‘h’ has the largest ASCII value.

>>> D={'a':10,'B':20,'h':30}
>>> max(D)

119
'h'

11. min()
min() function returns the smallest key from the dictionary.
>>> D={1: 10, 2: 20, 3: 30, 4: 40}
>>> min(D)
1
If keys are string, here ‘B’ has the largest ASCII value.
>>> D={'a':10,'B':20,'h':30}
>>> min(D)
'B'

12. fromkeys()
The fromkeys() method creates and returns a dictionary. It is useful when we want to create a dictionary
with multiple keys which have the same value.
Syntax: dict.fromkeys(keys, value)

>>> K=('A','B','C')
>>> V=10
>>> D=dict.fromkeys(K,V)
>>> D
{'A': 10, 'B': 10, 'C': 10}

13. copy()
The copy() method returns a copy of the specified dictionary.
dictionary.copy()

>>> D={1:10,2:20}
Create a copy of dictionary D and store in D1
>>> D1=D.copy()
>>> D1
{1: 10, 2: 20}

14. sorted()
sorted() function sort the dictionary keys in ascending order

>>> D={1:10,4:40,3:30,2:20}
Return the keys of dictionary in sorted order
>>> sorted(D)
[1, 2, 3, 4]
Return the keys of dictionary in sorted order
>>> sorted(D.keys())
[1, 2, 3, 4]

120
Return the values of dictionary in sorted order
>>> sorted(D.values())
[10, 20, 30, 40]
Return the (key, value) pairs of dictionary in sorted order
>>> sorted(D.items())
[(1, 10), (2, 20), (3, 30), (4, 40)]

Suggested Programs:

Program-1 : Write a Program in Python to count the number of times a character appears in a given
string using a dictionary.

S=input("Enter a string: ")


D={}
for c in S:
if c in D:
D[c]+=1
else:
D[c]=1
print("Frequency of Characters in String: \n",D)

Output:
Enter a string: S P SHARMA
Frequency of Characters in String:
{'S': 2, ' ': 2, 'P': 1, 'H': 1, 'A': 2, 'R': 1, 'M': 1}

Program-2 : Write a Program in Python to create a dictionary with names of employees, their salary
and access them

Emp = { }
while True :
name = input("Enter employee name : ")
salary = int(input("Enter employee salary : "))
Emp[name] = salary
c = input("Do you want to add more employee details(y/n) :")
if c not in "yY" :
break
print(Emp)

121
Output:
Enter employee name : Amit
Enter employee salary : 20000
Do you want to add more employee details(y/n) :y
Enter employee name : Sachin
Enter employee salary : 25000
Do you want to add more employee details(y/n) :y
Enter employee name : Saanvi
Enter employee salary : 28000
Do you want to add more employee details(y/n) :n
{'Amit': 20000, 'Sachin': 25000, 'Saanvi': 28000}

122

You might also like