0% found this document useful (0 votes)
25 views16 pages

# Addition of List Elements.

The document discusses various operations that can be performed on Python data structures like lists, tuples, dictionaries, strings and sets. It contains examples of adding, removing, modifying and extracting elements from these data structures. Various functions related to these data types are also demonstrated.
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)
25 views16 pages

# Addition of List Elements.

The document discusses various operations that can be performed on Python data structures like lists, tuples, dictionaries, strings and sets. It contains examples of adding, removing, modifying and extracting elements from these data structures. Various functions related to these data types are also demonstrated.
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/ 16

# Addition of list elements..

lst1 = [1,2,3,4,5,85]

addition = sum(lst1)

print(“Addition of elements in list:”,addition)

#GROUP 1ST……

1.Multiplication of list elements..

Lst1 = [1,2,3,4,5]

Multiplication = 1

For x in lst1:

Multiplication *= x

Print(“Multiplication of elements in list:”,multiplication)

2.Largest of list elements..

Lst1 = [1,2,3,4,5]

Max = max(Lst1)

print(“Maximum:”,Max)

3.Smallest of list elements..

Lst1 = [1,2,3,4,5]

Min = min(Lst1)

print(“Minimum:”,Min)

4.Count number of strings where string length is two or more and the first and last character are
same..

lst1 = [“vaibhav”, “vishwajeet”, “pallavi”, “anushka”,”vivek”]

count = 0

for i in lst1:

if isinstance (i,str) and len(i) > 1 and i[0] == i[-1]:

count += 1
print(i)

print(count)

5.Remove duplicates from list..

lst1 = [1,2,3,4,5,4,6,3,7,8]

uncommon = set(lst1)

print(“uncommon items from list:”,uncommon)

6.Check whether list is empty or not..

lst1 = []

if len(lst1) == 0:

print(“empty list!”)

else:

for i in lst1:

print(i)

7.Creating clone of list..

lst2 = [9,8,7,6,3,5,4]

copied_list = lst2.copy()

print(copied_list)

8.Removing even numbers from list..

lst1 = [1,2,3,4,5,6,7,8,9]

for i in lst1:

if (i%2 != 0):

print(i)

9.Checking common item from two lists accepted as input from user..

lst1 = input(“enter elements of list1:”)


lst2 = input(“enter elements of list2:”)

lst1 = lst1.split(‘,’)

lst2 = lst2.split(‘,’)

lst1 = [element.strip() for element in lst1]

lst2 = [element.strip() for element in lst2]

common = set(lst1) & set(lst2)

if len(common) == 0:

print(“No common”)

else:

print(common)

10.Remove 0th, 4th and 5th indexed elements from list..

lst1 = [1,2,3,4,5,6,7,8]

print(lst1)

lst1.pop(0)

print(lst1)

lst1.pop(4)

print(lst1)

lst1.pop(5)

print(lst1)

________________________________________

#GROUP 2ND………

1.Create and reverse a tuple..

tpl = (1,2,3,4,"Sayantani",6.3)
print(tpl)

reversed_tuple = tpl[::-1]

print(reversed_tuple)

2. Accessing value from tuple..

tpl = (1,2,3,4,20,6.3)

print(tpl)

print(tpl.index(20))

3.Create a tuple with only item 50..

Tpl = (50)

print(Tpl)

4. Unpack the tuple in 4 variables..

tpl = (1,2,3,4,5,6,7,8,9)

var1, var2, var3, var4, *remaining = tpl

print(var1)

print(var2)

print(var3)

print(var4)

print(remaining)

5.Swap two tuples..

tpl1 = (1,2,3,4)

tpl2 = (9,8,7,6)

temp = ()

temp = tpl1

tpl1 = tpl2
tpl2 = temp

print(tpl1)

print(tpl2)

# Or

tpl1 = (1,2,3,4)

tpl2 = (9,8,7,6)

tpl1, tpl2 = tpl2, tpl1

print(tpl1)

print(tpl2)

6.Copy specific elements from one tuple to another..

tpl1 = (0,1,2,3,4)

tpl2 = (9,8,7,6,5)

Mixed_tpl = tpl1 + tpl2[1:-1]

print(Mixed_tpl)

7.Modify the tuple..

tpl1 = (0,1,2,3,4)

# Add new elements to existing tuple..

New_tpl = tpl1[:5] + (5,6,7,8)

print(New_tuple)

8. Count number of occurrences of item in tuple..

tpl = (10,20,50,30,40,50)
cnt = tpl.count(50)

print(cnt)

9.Check if all items in tuple are same..

tpl = (9,9,9,9,9)

flag = False

for i in tpl:

if (i == tpl[0]):

flag = True

else:

flag = False

if flag == True:

print(“All are same”)

else:

print(“All elements are not identical”)

________________________________________

#GROUP 3RD………

1.Convert 2 lists into a dictionary..

lst1 = [1,2,3,4,5]

lst2 = [“A”,”B”,”C”,”D”,”E”]

dict1 = dict(zip(lst1,lst2))

print(dict1)

2.Merge two dictionaries..

dict1 = {1:”A”,2:”B”,3:”C”,4:”D”,5:”E”}
dict2 = {6:”F”,7:”G”,8:”H”,9:”I”}

dict1.update(dict2)

print(dict1)

3.Access value of specified key..

dict1 = {“English”:94,”Physics”:91,”Chemistry”:89,”Biology”:96,”History”:92}

print(dict1[“History])

4.Initialize dictionary with default values..

dict1 = {“A”,”B”,”C”}

initialized = dict.fromkeys(dict1,0)

print(initialized)

5.Create a new dictionary by extracting the keys from given dictionary..

mydict = {“roll”:63,”name”:”Vaibhav”,”marks”:35,”branch”:”com”}

keys = [“roll”,”name”]

dict2 = { k : mydict[k] for k in keys}

print(dict2)

6. Delete list of keys from dictionary..

#For single key:

dict1 = {1:”A”,2:”B”,3:”C”}

removable = (2)

del dict1[removable]

print(dict1)

#For multiple keys:

dict1 = {1:”A”,2:”B”,3:”C”}

removables = [1,3]
for key in removables:

if key in dict1:

del dict1 [key]

print(dict1)

7.Check if value exists in dictionary..

dict1 = {1:”A”,2:”B”,3:”C”}

keys = [3,5,2,1,6,8]

for value in keys:

if value in dict1:

print(“Exist”)

else:

print(“Does not exist”)

8.Rename key of a dictionary..

dict1 = {“key”:”value”}

new = dict1.pop(“key”)

dict1 [“new_key”] = new

print(dict1)

9.Get a key of minimum value from given dictionary..

dict1 = {“a”:1,”b”:2,”c”:3,”d”:4}

minimum = min(dict1.items())

print(minimum)

________________________________________

GROUP 4TH………
1.Create string made up of first, middle and last characters..

str1 = “Vaibhav”

print(“Original string:”, str1)

str_comb = str1[0] + str1[len(str1)//2] + str1[-1]

print(“Extracted string:”,str_comb)

2.Create string made up of middle three characters..

str1 = “Vaibhav”

print(“Original string:”, str1)

modified_str = str1[(len(str1)//2)-1] + str1[(len(str1)//2)] + str1[(len(str1)//2)+1]

print(“Extracted string:”,modified_str)

3.Append new string in the middle of the given string..

str1 = “Vaibhav”

string_to_append = “ana”

middle = len(str1)//2

appended_str = str1[:middle] + string_to_append + str1[middle:]

print(appended_str)

4. Create string made up of first, middle and last characters of input string..

str1 = str(input(“Enter string input:”))

print(“Original string:”, str1)

str_comb = str1[0] + str1[len(str1)//2] + str1[-1]

print(“Extracted string:”,str_comb)

5. Arrange string characters such as lowercase characters should come first..

# Not arranging capitals

str1 = “ajdhePraejoAksSMskbhavnejwjwaliVai”

str2 = sorted(str1.lower()) + list(str1.upper())


print(str2)

#.Arranging capitals too

str2 = sorted(str1.lower()) + sorted(str1.upper())

print(str2)

6.Count all letters, digits and special symbols from a given string..

str1 = “ajaiiee6e_an@vaiket:)ali3m!”

l_count = 0

ss_count = 0

d_count = 0

for element in str1:

if element.isalpha():

l_count += 1

elif element.isdigit():

d_count += 1

else:

ss_count += 1

print(l_count)

print(d_count)

print(ss_count)

#Extract substring from given list of strings which has been ended with letter ‘s’..

strings = [“Jarvis”,”Friday”,”Alexis”,”Frances”,”Paris”,”Thomas”]

for items in strings:

if items.endswith(‘s’):

string_sliced = items[:-1]

print(string_sliced)
67.String character balance test..

str1 = str(input(“Enter string1:”))

str2 = str(input(“Enter string2:”))

flag = False

if len(str1)==len(str2):

for I in str1:

if I in str2:

flag = True

else:

flag = False

if flag == True:

print(“Strings are balanced”)

else:

print(“Strings are not balanced”)

8.Finding occurance of substring in given string by ignoring case..

string_input = str(input(“Enter String:”))

str1 = string_input.lower()

print(str1)

occ_count = 0

substring = “what if”

if substring in string_input:

occ_count += 1

print(occ_count)

9.Finding occurance of all characters in given string by ignoring case..

string_input = str(input("Enter String:"))

str1 = list(string_input.lower())

occ_count = {}
for substring in str1:

if substring in occ_count:

occ_count[substring] += 1

else:

occ_count[substring] = 1

print(occ_count)

10.Calculate sum and average of digits present in a string..

string_input = str(input(“Enter string: ”))

summation = 0

average = 0

no_of_digits = 0

if string_input.isdigit() == True:

for i in string_input:

no_of_digits += 1

summation += int(i)

average = summation/no_of_digits

print(summation)

print(average)

_________________________________________

#GROUP 5TH…………

1.Create a function in python..

def add(x,y,z=0):

z=x+y

return z

result = add(10,20)
print("Addition:",result)

2.Create a function with variable length arguments in python..

def funct1(*args):

addition = 0

for i in args:

addition += i

return addition

print("Addition:",funct1(1,2,3,4,5))

3.Return multiple values from a function..

def func1(x,y,z):

return x,y,z

print(func1(1,2,3))

4. Create a function with default arguments..

def func1(a,b,default=48):

return (a+b+default)

print(func1(4,2))

5.Create inner function to calculate addition of variables in outer function..

def outer_f(a,b):

def inner_f(addition=0):

addition = a + b

return addition

print(inner_f())

outer_f(6,48)

6.Create a recursive function..


def factorial(num):

if num == 0 or num == 1:

return 1

else:

return num * factorial(num - 1)

print(factorial(5))

7.Assign different name to function and call it through the new name..

def demo():

print("Demo function")

new_demo = demo

print(new_demo())

8.Generate python list of all even numbers b/w 4 to 30..

def even_no(start,end):

e_lst = []

for num in range(start,end+1):

if (num%2) == 0:

e_lst.append(num)

print(e_lst)

even_no(4,30)

9.Find the largest item from given list..

def largest(lst):

maximum = max(lst)

return maximum

lst = [20,48,26,45]

print(largest(lst))
________________________________________

GROUP 6TH………

1.Creating set and adding elements in it

myset = {“pink”, “green”, “yellow”, 6, 3, 4.8}

print(myset)

2.Identical elements from two sets

myset1 = {“pink”, “green”, “yellow”, 6, 3, 4.8}

myset2 = {“red”, “yellow”, “green”, 5, 3, 2.6}

print(myset1.intersection(myset2))

3.Unique elements from two sets

myset1 = {“pink”, “green ”, “yellow”, 6, 3, 4.8}

myset2 = {“red”, “yellow”, “green”, 5, 3, 2.6}

print(myset1.union (myset2))

4.Update the first set with elements that don’t exist in second set

Myset1 = {1, 2, 3, 4, 5}

Myset2 = {4, 5, 6, 7, 8}

Myset1.update(myset2 -myset1)

Print(myset1)

5.Remove items from the set at once

myset1 = {1, 2, 3, 4, 5}

items_to_remove = {4, 5}
myset1.difference_update(items_to_remove)

print(myset1)

6.Return set of elements present in set A or set B but not in both

A = {1, 2, 3, 4, 5}

B = {4, 5, 6, 7, 8}

print(A.union(B))

7.Check if two sets have common items, if yes display them

myset1 = {1, 2, 3, 4, 5}

myset2 = {9, 8, 7, 6, 5}

myset3 = myset1.intersection(myset2)

if (myset1.intersection(myset2)) != {}:

print(“Common items:”,myset3)

8.Update set1 by adding items from set2 except common onces

myset1 = {1, 2, 3, 4, 5, 6}

myset2 = {6, 7, 8, 9, 0, 1}

myset1.update(myset2)

print(myset1)

9.Remove items from set1 that are not common in both set1 and set2

myset1 = {1, 2, 3, 4, 5, 6}

myset2 = {6, 7, 8, 9, 0, 1}

myset2.difference(myset1)

print(myset2)

_______*******_______*__*_*_**__*_*_*_*_*_*_**__*_*_*__*_*

You might also like