Python tuple: Exercise-1 with Solution
Write a Python program to create a tuple.
Sample Solution:-
Python Code:
#Create an empty tuple
x = ()
print(x)
#Create an empty tuple with tuple() function built-in Python
tuplex = tuple()
print(tuplex)
Sample Output:
()
()
Python tuple: Exercise-2 with Solution
Write a Python program to create a tuple with different data types.
Sample Solution:-
Python Code:
#Create a tuple with different data types
tuplex = ("tuple", False, 3.2, 1)
print(tuplex)
Sample Output:
('tuple', False, 3.2, 1)
Python tuple: Exercise-3 with Solution
Write a Python program to create a tuple with numbers and print one item.
Sample Solution:-
Python Code:
#Create a tuple with numbers
tuplex = 5, 10, 15, 20, 25
print(tuplex)
#Create a tuple of one item
tuplex = 5,
print(tuplex)
Sample Output:
(5, 10, 15, 20, 25)
(5,)
Python tuple: Exercise-4 with Solution
Write a Python program to add an item in a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = (4, 6, 2, 8, 3, 1)
print(tuplex)
#tuples are immutable, so you can not add new elements
#using merge of tuples with the + operator you can add an element and it will create
a new tuple
tuplex = tuplex + (9,)
print(tuplex)
#adding items in a specific index
tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to add items in list
listx.append(30)
tuplex = tuple(listx)
print(tuplex)
Sample Output:
(4, 6, 2, 8, 3, 1)
(4, 6, 2, 8, 3, 1, 9)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3)
(4, 6, 2, 8, 3, 15, 20, 25, 4, 6, 2, 8, 3, 30)
Python tuple: Exercise-5 with Solution
Write a Python program to convert a tuple to a string.
Sample Solution:-
Python Code:
tup = ('e', 'x', 'e', 'r', 'c', 'i', 's', 'e', 's')
str = ''.join(tup)
print(str)
Sample Output:
exercises
Python tuple: Exercise-6 with Solution
Write a Python program to get the 4th element and 4th element from last of a
tuple.
Sample Solution:-
Python Code:
#Get an item of the tuple
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print(tuplex)
#Get item (4th element)of the tuple by index
item = tuplex[3]
print(item)
#Get item (4th element from last)by index negative
item1 = tuplex[-4]
print(item1)
Sample Output:
('w', 3, 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
e
u
Python tuple: Exercise-7 with Solution
Write a Python program to check whether an element exists within a tuple.
Sample Solution:-
Python Code:
tuplex = ("w", 3, "r", "e", "s", "o", "u", "r", "c", "e")
print("r" in tuplex)
print(5 in tuplex)
Sample Output:
True
False
Python tuple: Exercise-8 with Solution
Write a Python program to find the repeated items of a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = 2, 4, 5, 6, 2, 3, 4, 4, 7
print(tuplex)
#return the number of times it appears in the tuple.
count = tuplex.count(4)
print(count)
Sample Output:
(2, 4, 5, 6, 2, 3, 4, 4, 7)
3
Python tuple: Exercise-9 with Solution
Write a Python program to convert a list to a tuple.
Sample Solution:-
Python Code:
#Convert list to tuple
listx = [5, 10, 7, 4, 15, 3]
print(listx)
#use the tuple() function built-in Python, passing as parameter the list
tuplex = tuple(listx)
print(tuplex)
Sample Output:
[5, 10, 7, 4, 15, 3]
(5, 10, 7, 4, 15, 3)
Python tuple: Exercise-10 with Solution
Write a Python program to remove an item from a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = "w", 3, "r", "s", "o", "u", "r", "c", "e"
print(tuplex)
#tuples are immutable, so you can not remove elements
#using merge of tuples with the + operator you can remove an item and it will create
a new tuple
tuplex = tuplex[:2] + tuplex[3:]
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("c")
#converting the tuple to list
tuplex = tuple(listx)
print(tuplex)
Sample Output:
('w', 3, 'r', 's', 'o', 'u', 'r', 'c', 'e')
('w', 3, 's', 'o', 'u', 'r', 'c', 'e')
('w', 3, 's', 'o', 'u', 'r', 'e')
Python tuple: Exercise-11 with Solution
Write a Python program to slice a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = (2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
#used tuple[start:stop] the start index is inclusive and the stop index
slice = tuplex[3:5]
#is exclusive
print(_slice)
#if the start index isn't defined, is taken from the beg inning of the tuple
_slice = tuplex[:6]
print(_slice)
#if the end index isn't defined, is taken until the end of the tuple
_slice = tuplex[5:]
print(_slice)
#if neither is defined, returns the full tuple
_slice = tuplex[:]
print(_slice)
#The indexes can be defined with negative values
_slice = tuplex[-8:-4]
print(_slice)
#create another tuple
tuplex = tuple("HELLO WORLD")
print(tuplex)
#step specify an increment between the elements to cut of the tuple
#tuple[start:stop:step]
_slice = tuplex[2:9:2]
print(_slice)
#returns a tuple with a jump every 3 items
_slice = tuplex[::4]
print(_slice)
#when step is negative the jump is made back
_slice = tuplex[9:2:-4]
print(_slice)
Sample Output:
(5, 4)
(2, 4, 3, 5, 4, 6)
(6, 7, 8, 6, 1)
(2, 4, 3, 5, 4, 6, 7, 8, 6, 1)
(3, 5, 4, 6)
('H', 'E', 'L', 'L', 'O', ' ', 'W', 'O', 'R', 'L', 'D')
('L', 'O', 'W', 'R')
('H', 'O', 'R')
('L', ' ')
Python tuple: Exercise-12 with Solution
Write a Python program to find the index of an item of a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = tuple("index tuple")
print(tuplex)
#get index of the first item whose value is passed as parameter
index = tuplex.index("p")
print(index)
#define the index from which you want to search
index = tuplex.index("p", 5)
print(index)
#define the segment of the tuple to be searched
index = tuplex.index("e", 3, 6)
print(index)
#if item not exists in the tuple return ValueError Exception
index = tuplex.index("y")
Sample Output:
('i', 'n', 'd', 'e', 'x', ' ', 't', 'u', 'p', 'l', 'e')
8
8
3
Traceback (most recent call last):
File "d0e5ee40-30ab-11e7-a6a0-0b37d4d0b2c6.py", line 14, in
<module>
index = tuplex.index("y")
ValueError: tuple.index(x): x not in tuple
Python tuple: Exercise-13 with Solution
Write a Python program to find the length of a tuple.
Sample Solution:-
Python Code:
#create a tuple
tuplex = tuple("w3resource")
print(tuplex)
#use the len() function to known the length of tuple
print(len(tuplex))
Sample Output:
('w', '3', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e')
10
Python sets: Exercise-1 with Solution
Write a Python program to create a new empty set.
Sample Solution:-
Python Code:
#Create a new empty set
x = set()
print(x)
#Create a non empty set
n = set([0, 1, 2, 3, 4])
print(n)
Sample Output:
set()
{0, 1, 2, 3, 4}
Python sets: Exercise-2 with Solution
Write a Python program to iteration over sets.
Sample Solution:-
Python Code:
#Create a set
num_set = set([0, 1, 2, 3, 4, 5])
for n in num_set:
print(n)
Sample Output:
0
1
2
3
4
5
Python sets: Exercise-3 with Solution
Write a Python program to add member(s) in a set.
Sample Solution:-
Python Code:
#A new empty set
color_set = set()
color_set.add("Red")
print(color_set)
#Add multiple items
color_set.update(["Blue", "Green"])
print(color_set)
Sample Output:
{'Red'}
{'Red', 'Blue', 'Green'}
Python sets: Exercise-4 with Solution
Write a Python program to remove item(s) from set.
Sample Solution:-
Python Code:
num_set = set([0, 1, 3, 4, 5])
num_set.pop()
print(num_set)
num_set.pop()
print(num_set)
Sample Output:
{1, 3, 4, 5}
{3, 4, 5}
Python sets: Exercise-5 with Solution
Write a Python program to remove an item from a set if it is present in the set.
Sample Solution:-
Python Code:
#Create a new set
num_set = set([0, 1, 2, 3, 4, 5])
#Discard number 4
num_set.discard(4)
print(num_set)
Sample Output:
{0, 1, 2, 3, 5}
Python sets: Exercise-6 with Solution
Write a Python program to create an intersection of sets.
Sample Solution:-
Python Code:
#Intersection
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
setz = setx & sety
print(setz)
Sample Output:
{'blue'}
Python sets: Exercise-7 with Solution
Write a Python program to create a union of sets.
Sample Solution:-
Python Code:
#Union
setx = set(["green", "blue"])
sety = set(["blue", "yellow"])
seta = setx | sety
print(seta)
Sample Output:
{'yellow', 'green', 'blue'}
Python sets: Exercise-8 with Solution
Write a Python program to create set difference.
Sample Solution:-
Python Code:
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = setx & sety
print(setz)
#Set difference
setb = setx - setz
print(setb)
Sample Output:
{'mango'}
{'apple'}
Python sets: Exercise-9 with Solution
Write a Python program to clear a set.
Sample Solution:-
Python Code:
setp = set(["Red", "Green"])
setq = setp.copy()
print(setq)
setq.clear()
print(setq)
Sample Output:
{'Green', 'Red'}
set()
Python sets: Exercise-10 with Solution
Write a Python program to find maximum and the minimum value in a set.
Sample Solution:-
Python Code:
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find maximum value
print(max(seta))
#Find minimum value
print(min(seta))
Sample Output:
20
2
Python sets: Exercise-11 with Solution
Write a Python program to find the length of a set.
Sample Solution:-
Python Code:
#Create a set
seta = set([5, 10, 3, 15, 2, 20])
#Find the length use len()
print(len(seta))
Sample Output:
6
Python dictionary: Exercise-1 with Solution
Write a Python program to add a key to a dictionary.
Sample Solution:-
Python Code:
d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)
Sample Output:
{0: 10, 1: 20}
{0: 10, 1: 20, 2: 30}
Python dictionary: Exercise-2 with Solution
Write a Python program to check if a given key already exists in a dictionary.
Sample Solution:-
Python Code:
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)
is_key_present(9)
Sample Output:
Key is present in the dictionary
Key is not present in the dictionary
Python dictionary: Exercise-3 with Solution
Write a Python script to print a dictionary where the keys are numbers between 1
and 15 (both included) and the values are square of keys.
Sample Solution:-
Python Code:
d=dict()
for x in range(1,16):
d[x]=x**2
print(d)
Sample Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10:
100, 11: 121, 12: 144, 13: 169, 14: 196, 15:
225}
Python dictionary: Exercise-4 with Solution
Write a Python script to merge two Python dictionaries.
Sample Solution:-
Python Code:
d1 = {'a': 100, 'b': 200}
d2 = {'x': 300, 'y': 200}
d = d1.copy()
d.update(d2)
print(d)
Sample Output:
{'x': 300, 'y': 200, 'a': 100, 'b': 200}
Python dictionary: Exercise-5 with Solution
Write a Python program to iterate over dictionaries using for loops.
Sample Solution:-
Python Code:
d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
print(color_key, 'corresponds to ', d[color_key])
Sample Output:
Red corresponds to 1
Blue corresponds to 3
Green corresponds to 2
Python dictionary: Exercise-6 with Solution
Write a Python program to sum all the items in a dictionary.
Sample Solution:-
Python Code:
my_dict = {'data1':100,'data2':-54,'data3':247}
print(sum(my_dict.values()))
Sample Output:
293
Python dictionary: Exercise-7 with Solution
Write a Python program to multiply all the items in a dictionary.
Sample Solution:-
Python Code:
my_dict = {'data1':100,'data2':-54,'data3':247}
result=1
for key in my_dict:
result=result * my_dict[key]
print(result)
Sample Output:
-1333800
Python dictionary: Exercise-8 with Solution
Write a Python program to map two lists into a dictionary.
Sample Solution:-
Python Code:
keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)
Sample Output:
{'green': '#008000', 'blue': '#0000FF', 'red': '#FF0000'}
Python dictionary: Exercise-9 with Solution
Write a Python program to sort a dictionary by key.
Sample Solution:-
Python Code:
color_dict = {'red':'#FF0000',
'green':'#008000',
'black':'#000000',
'white':'#FFFFFF'}
for key in sorted(color_dict):
print("%s: %s" % (key, color_dict[key]))
Sample Output:
black: #000000
green: #008000
red: #FF0000
white: #FFFFFF
Python dictionary: Exercise-10 with Solution
Write a Python program to get the maximum and minimum value in a dictionary.
Sample Solution:-
Python Code:
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
Sample Output:
Maximum Value: 5874
Minimum Value: 500
Python dictionary: Exercise-11 with Solution
Write a Python program to find the highest 3 values in a dictionary.
Sample Solution:-
Python Code:
from heapq import nlargest
my_dict = {'a':500, 'b':5874, 'c': 560,'d':400, 'e':5874, 'f': 20}
three_largest = nlargest(3, my_dict, key=my_dict.get)
print(three_largest)
Sample Output:
['e', 'b', 'c']
Python dictionary: Exercise-12 with Solution
Write a Python program to get the key, value and item in a dictionary.
Sample Solution:-
Python Code:
dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
print("key value count")
for count, (key, value) in enumerate(dict_num.items(), 1):
print(key,' ',value,' ', count)
Sample Output:
key value count
1 10 1
2 20 2
3 30 3
4 40 4
5 50 5
6 60 6