Module 2 Programs: List, Tuple and String
Note: Program number 1 and 2 can perform in interactive shell
1. Consider the given list and perform the following operation
[3,’hi’,5.0,None,True,6,8,10]
Create a new sublist from ‘hi’ to True
[3, 'hi', 5.0, None, True, 6, 8, 10][1:5]
Or
spam=[3, 'hi', 5.0, None, True, 6, 8, 10]
print(spam[1:5])
Or
spam=[3, 'hi', 5.0, None, True, 6, 8, 10]
spam[1:5]
Output:
['hi', 5.0, None, True]
Print items from starting to end using slice operation.
[3, 'hi', 5.0, None, True, 6, 8, 10][ : ]
Output:
[3, 'hi', 5.0, None, True, 6, 8, 10]
Use –ve index to extract a new sublist from True to 10
[3, 'hi', 5.0, None, True, 6, 8, 10][-4:]
Output:
[True, 6, 8, 10]
Print all even indexed item from the list
spam=[3, 'hi', 5.0, None, True, 6, 8, 10]
spam[0: :2]
or
spam[0:8:2]
Output:
[3, 5.0, True, 8]
Find the length of the list.
len(spam)
Output:
8
Update the value of 5.0 to ‘how are you?’
spam[2]='how are you?'
spam
Output:
[3, 'hi', 'how are you?', None, True, 6, 8, 10]
2. Concatenate the given two list [‘A’,’B’,’C’] and [1,2,3] into new string and store the result
in variable ‘spam’ and print the value.
spam=['A','B','C']
cheese=[1,2,3]
list=spam+cheese
list
Output:
['A', 'B', 'C', 1, 2, 3]
3. Write a program to create a list, read items to the list and find sum of items in the list.
Print the even number in the list using functions and print the reversed list.
def sum(a):
sum=0
for i in a:
sum=sum+i
return sum
def eve(a):
for i in a:
if i%2==0:
list.append(i)
print(list)
return
list1=[]
list=[]
n=int(input('Enter limit'))
for i in range(n):
num=int(input())
list1.append(num)
print(list1)
s=sum(list1)
print('sum is:',s)
print('even numbers in the list are:')
eve(list1)
list.sort(reverse=True)
print(list)
Output:
Enter limit5
1
2
3
4
5
[1, 2, 3, 4, 5]
sum is: 15
even numbers in the list are:
[2, 4]
[4, 2]
4. Write a python program to generate prime numbers upto ‘n’ and store them to a list.
Display the first 5 elements using slice and display last 5 items using slice.
p=[ ]
n=int(input('Enter the range: '))
for c in range(2,n):
flag=0
for i in range(2,c):
if c%i==0:
flag=1
break
if flag==0:
p.append(c)
print('The first 5 numbers in the list are:')
print(p[0:5])
print('The last 5 prime numbers in the list are;')
print(p[-1:-6:-1])
Output:
Enter the range: 15
The first 5 numbers in the list are:
[2, 3, 5, 7, 11]
The last 5 prime numbers in the list are;
[13, 11, 7, 5, 3]
5. Write a program to read student names to the created list until enter nothing or space.
studNames = []
while True:
print('Enter the name of cat ' + str(len(studNames) + 1) + '(Or enter nothing to stop.):')
name = input()
if name == '':
break
studNames = studNames + [name] # list concatenation
print('The Student names are:')
for name in studNames:
print(' ' + name)
Output:
Enter the name of cat 1(Or enter nothing to stop.):
alice
Enter the name of cat 2(Or enter nothing to stop.):
bob
Enter the name of cat 3(Or enter nothing to stop.):
spam
Enter the name of cat 4(Or enter nothing to stop.):
cheese
Enter the name of cat 5(Or enter nothing to stop.):
The Student names are:
alice
bob
spam
cheese
6. Create a list of petnames, read the name and check that name is present in the list or not
and print the appropriate message.
myPets = ['Zophie', 'Pooka', 'Fat-tail']
print('Enter a pet name:')
name = input()
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
Output1:
Enter a pet name:
scooby
I do not have a pet named Scooby
Output2:
Enter a pet name:
pooka
I do not have a pet named pooka
Output3:
Enter a pet name:
Pooka
Pooka is my pet.
7. Read ‘n’ numbers to a list sort list in ascending and descending order respectively.
list=[ ]
n=int(input('Enter number of items to the list : '))
for i in range(n):
num=int(input('Enter the number : '))
list.append(num)
print(list)
print('The list after sorting in ascending order')
list.sort()
print(list)
print('The list after sorting in descending order')
list.sort(reverse=True)
print(list)
Output:
Enter number of items to the list : 6
Enter the number : 5
Enter the number : 3
Enter the number : 1
Enter the number : 7
Enter the number : 4
Enter the number : 5
[5, 3, 1, 7, 4, 5]
The list after sorting in ascending order
[1, 3, 4, 5, 5, 7]
The list after sorting in descending order
[7, 5, 5, 4, 3, 1]
8. Write a program to read ‘n’ strings to the list. Sort in ASCIIbetical and alphabetical
order.
p=[]
n=int(input('Enter the number of strings to the list : '))
for i in range(n):
print('Enter the string')
k=input()
p.append(k)
print(p)
print('The list after sorting in ASCIIbetical order:')
p.sort()
print(p)
print('The list after sorting in alphabetical order:')
p.sort(key=str.lower)
print(p)
Output:
Enter the number of strings to the list : 5
Enter the string
a
Enter the string
z
Enter the string
A
Enter the string
Z
Enter the string
B
['a', 'z', 'A', 'Z', 'B']
The list after sorting in ASCIIbetical order:
['A', 'B', 'Z', 'a', 'z']
The list after sorting in alphabetical order:
['A', 'a', 'B', 'Z', 'z']
9. Perform the basic operations like finding index, slicing, print the length of the tuple and
use type function to find data type of the given tuple.
t=('Hi','Alice',0.5,23)
print('The tuple :')
print(t)
print('The index of Alice is :')
print(t.index('Alice'))
print('sub tuple from index 1 to 4 is')
print(t[1:4:1])
print('len of the tuple is :', len(t))
Output:
The tuple :
('Hi', 'Alice', 0.5, 23)
The index of Alice is :
1
sub tuple from index 1 to 4 is
('Alice', 0.5, 23)
len of the tuple is : 4
<class 'tuple'>
10. Perform the basic operations like finding index, slicing, print the length of the string
and use type function to find data type of the given string.
name='Zophie'
print('The String is :')
print(name)
print('The index of character p is :')
print(name.index('p'))
print('sub string from index 0 to 4 is')
print(name[0:4:1])
print('len of the string is :', len(name))
print(type(name))
Output:
The String is :
Zophie
The index of character p is :
2
sub string from index 0 to 4 is
Zoph
len of the string is : 6
<class 'str'>
11. Copy program
import copy
list1 = [11, 22, 33, 44, 55]
list2 = copy.copy(list1)
list3 = copy.copy(list2)
print(list1)
print(list2)
print(list3)
print(' list1 reference = ', id(list1))
print(' list2 reference = ', id(list2))
print(' list3 reference = ', id(list3))
list3[2] = 999
print(list1)
print(list2)
print(list3)
list2[1] = 888
print(list1)
print(list2)
print(list3)
Output:
[11, 22, 33, 44, 55]
[11, 22, 33, 44, 55]
[11, 22, 33, 44, 55]
list1 reference = 2357165907072
list2 reference = 2357165707840
list3 reference = 2357165709056
[11, 22, 33, 44, 55]
[11, 22, 33, 44, 55]
[11, 22, 999, 44, 55]
[11, 22, 33, 44, 55]
[11, 888, 33, 44, 55]
[11, 22, 999, 44, 55]
12. Deep Copy Program
import copy
list1 = [[11, 22, 33], [44, 55]]
list2 = list1
list3 = copy.copy(list1)
list4 = copy.deepcopy(list1)
print('LIST1 = ', list1)
print('LIST2 = ', list2)
print('LIST3 = ', list3)
print('LIST4 = ', list4)
print('list1 reference = ', id(list1))
print('list2 reference = ', id(list2))
print('list3 reference = ', id(list3))
print('list4 reference = ', id(list4))
list3[0] = 888 # does not reflect other two lists - sublist
list3[1][1] = 777 # reflects other two lists – item in sublist
list4[0] = 666 # does not reflect other two lists - sublist
list4[1][1] = 333 # does not reflects other two lists – item in sublist
list1.append([9, 8, 7])
print('LIST1 = ', list1)
print('LIST2 = ', list2)
print('LIST3 = ', list3)
print('LIST4 = ', list4)
Output:
LIST1 = [[11, 22, 33], [44, 55]]
LIST2 = [[11, 22, 33], [44, 55]]
LIST3 = [[11, 22, 33], [44, 55]]
LIST4 = [[11, 22, 33], [44, 55]]
list1 reference = 2155236342208
list2 reference = 2155236342208
list3 reference = 2155235912256
list4 reference = 2155236510336
LIST1 = [[11, 22, 33], [44, 777], [9, 8, 7]]
LIST2 = [[11, 22, 33], [44, 777], [9, 8, 7]]
LIST3 = [888, [44, 777]]
LIST4 = [666, [44, 333]]
13. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
Without using setdefault
dic={}
c=input('Enter the multi-digit number:')
for i in c:
if i not in dic:
dic[i]=1
else:
dic[i]+=1
print('Frequency of each digit is:')
print(dic)
Using setdefault
dic={}
c=input('Enter the multi-digit number:')
for i in c:
dic.setdefault(i,0)
dic[i]+=1
print('Frequency of each digit is:')
print(dic)
Output:
Enter the multi-digit number:245136892215
Frequency of each digit is:
{'2': 3, '4': 1, '5': 2, '1': 2, '3': 1, '6': 1, '8': 1, '9': 1}
14. Working of all the dictionary methods.
spam={'color':'red','age':42}
for i in spam.values():
print(i)
for v in spam.keys():
print(v)
for n in spam.items():
print(n)
for k,v in spam.items():
print('key:'+k+'Value:'+str(v))
spam['name']='Alice'
print(spam)
print(spam.get('age',0))
print(spam.get('size',0))
import itertools
new=dict(itertools.islice(spam.items(),2))
print(new)
Output:
red
42
color
age
('color', 'red')
('age', 42)
key:colorValue:red
key:ageValue:42
{'color': 'red', 'age': 42, 'name': 'Alice'}
42
0
{'color': 'red', 'age': 42}
15. program that counts the number of occurrences of each letter in a string using
setdefault.
import pprint
message='Hi how are you?'
dic={}
for i in message:
dic.setdefault(i,0)
dic[i]=dic[i]+1
print(dic)
print(‘Pretty format of dictionary is :’)
pprint.pprint(dic)
Output:
{'H': 1, 'i': 1, ' ': 3, 'h': 1, 'o': 2, 'w': 1, 'a': 1, 'r': 1, 'e': 1, 'y': 1, 'u': 1, '?': 1}
Pretty format of dictionary is :
{' ': 3,
'?': 1,
'H': 1,
'a': 1,
'e': 1,
'h': 1,
'i': 1,
'o': 2,
'r': 1,
'u': 1,
'w': 1,
'y': 1}