python ques
python ques
tasks = [
["Task A", 1, "Pending"],
["Task B", 2, "In Progress"],
["Task C", 1, "Pending"]
]
high_priority = [task[0] for task in tasks if task[1] == 1]
tasks[0][2] = "In Progress"
print(high_priority)
print(tasks)
Answer:
What is the output of this tuple unpacking and concatenation for a flight
itinerary?
flight = (101, ("JFK", "LAX"), ("2025-04-27", "08:00"))
(dep, arr), (date, _) = flight[1:]
new_itinerary = flight[:1] + ((dep, "SFO"),) + ((date, "10:00"),)
print(new_itinerary)
Answer:
{'Movie B'}
{'Movie A', 'Movie B'}
What is the output of this nested dictionary update for a booking system?
bookings = {
"Flight101": {"passenger": "Alice", "seats": ["A1", "A2"]},
"Flight102": {"passenger": "Bob", "seats": ["B1"]}
}
bookings["Flight101"]["seats"].append("A3")
bookings["Flight103"] = {"passenger": "Charlie", "seats": []}
print(bookings["Flight101"]["seats"])
print(len(bookings["Flight103"]["seats"]))
Answer:
What is the output of this list sorting with a custom key for a leaderboard?
players = [
{"name": "Alice", "score": 100, "time": 120},
{"name": "Bob", "score": 100, "time": 110},
{"name": "Charlie", "score": 90, "time": 130}
]
players.sort(key=lambda x: (-x["score"], x["time"]))
print([player["name"] for player in players])
Explanation: The sort() method uses a key function sorting by score (descending,
hence -x["score"]) and time (ascending) as a tiebreaker. Alice and Bob have the
same score (100), but Bob’s time (110) is less than Alice’s (120), so Bob comes
first. Charlie’s lower score (90) places him last. The comprehension extracts
names: ["Bob", "Alice", "Charlie"].
What is the output of this tuple in a set operation for unique coordinates?
points = {(1, 2), (3, 4), (1, 2)}
other_points = {(3, 4), (5, 6)}
unique_points = points.symmetric_difference(other_points)
print(unique_points)
Answer: {1, 3}
Explanation: The set comprehension creates a set of id values from products where
category is "Electronics". Products with IDs 1 and 3 match, so the result is {1,
3}. Sets are unordered, but the values are unique.
Answer:
What is the output of this nested list modification for a seating chart?
seating = [
["A1", "A2", None],
["B1", None, "B3"]
]
seating[0][2] = seating[1][0]
seating[1].pop(0)
print(seating)
Why can’t a list be used as a dictionary key, and what alternative would you use?
Alternative: Use a tuple, which is immutable and hashable, as a key if the list’s
contents are fixed.
Code:
Use Case: In a game, use a tuple key (position = (x, y)) to map coordinates to game
objects, ensuring immutability.
Q7: How would you reverse a list in Python, and what are the differences between
the methods?
Code:
lst = [1, 2, 3]
# Method 1: reverse()
lst_copy = lst.copy() # Avoid modifying original
lst_copy.reverse()
# lst_copy is [3, 2, 1]
# Method 2: slicing
reversed_lst = lst[::-1]
# reversed_lst is [3, 2, 1]
# Method 3: reversed()
reversed_lst2 = list(reversed(lst))
# reversed_lst2 is [3, 2, 1]
Differences:
In-Place vs. New List: reverse() modifies the original list, while [::-1] and
reversed() create new lists.
Memory: reverse() is memory-efficient (O(1) space), while [::-1] and reversed() use
O(n) space for the new list.
Flexibility: reversed() returns an iterator, useful for lazy evaluation.
Answer
sort( ) sorted( )
It modifies the list it is called on. That is, the sorted list is stored in the
same list; a new list is not created. It creates a new list containing a sorted
version of the list passed to it as argument. It does not modify the list passed as
a parameter.
It works on a list and modifies it. It can take any iterable sequence type, such as
a list or a tuple etc, and it always returns a sorted list irrespective of the type
of sequence passed to it.
It does not return anything (no return value). It modifies the list in place.
It returns a newly created sorted list. It does not change the passed
sequence.
What does each of the following expressions evaluate to? Suppose that L is the list
["These", ["are", "a", "few", "words"], "that", "we", "will", "use"].
L[1][0::2]
"a" in L[1][0]
L[:1] + L[1]
L[2::2]
L[2][2] in L[1]
Answer
['are', 'few']
True
['These', 'are', 'a', 'few', 'words']
['that', 'will']
True
Explanation
L[1] returns ["are", "a", "few", "words"]. L[1][0::2] returns a slice of ["are",
"a", "few", "words"] starting at index 0 covering every alternate element till the
end of the list. So, final output is ['are', 'few'].
L[1][0] is "are". As "a" is present in "are" so output is True.
L[:1] return L[0] i.e. ["These"]. L[1] returns ["are", "a", "few", "words"]. +
operator adds the two in a single list to give the final output as ['These', 'are',
'a', 'few', 'words'].
L[2::2] returns a slice of L starting at index 2 covering every alternate element
till the end of the list. So, final output is ['that', 'will'].
L[1] is ["are", "a", "few", "words"]. L[2][2] is "a". As "a" is present in L[1] so
output is True.
Solution
x = 1
for i in range(1, 41, 3) :
print(i * x, end = ' ')
x *= -1
What are the similarities and differences between tuples and lists?
i = 1
while i < 16:
if i % 3 == 0 :
print (i)
i += 1
min = 0
max = num
if num < 0 :
min = num
max = 0
# compute sum of integers from min to max
for i in range(min, max + 1):
sum += i
Answer
min = 0
max = num
if num < 0 :
min = num
max = 0
# compute sum of integers from min to max
i = min
while i <= max:
sum += i
i += 1
l = [1]
for x in l:
l.append(x + 1)
if num <= 0:
break
print (num % 10)
num = num/10
i = 100
while (i > 0) :
print i
i -= 3
Answer
Following code prints the given list in ascending order. Modify the code so that
the elements are printed in the reverse order of the result produced by the given
code.
Output
[0, 12, 24, 36, 48]
Explanation
list(range(0, 51, 4)) will create a list from 0 to 48 with a step of 4 so numbers
will be [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48]. For loop will traverse
the list one number at a time. if not number % 3 means if number % 3 is equal to 0
i.e. number is divisible by 3. The numbers divisible by 3 are added to the results
list and after the loop results list is printed.
Output
523
[]
<class 'list'> <class 'str'>
Explanation
The loop while x will continue executing as long as the length of list x is greater
than 0. y is initially an empty string. Inside the loop, we are adding the last
element of x to y and after that we are removing the last element of x from x. So,
at the end of the loop y becomes 523 and x becomes empty. Type of x and y are list
and str respectively.
L1 = [3, 4, 5]
L2 = L1 * 3
print(L1 * 3.0)
print(L2)
Answer
The line print(L1 * 3.0) causes an error as Python does not allow multiplying a
list with a non-int number and 3.0 is of float type.
An + 2 will cause an error because remove() function does not return the removed
element so An will be None. Addition operator (+) does not allow any of its
operands to be None hence, it will raise a TypeError.
Odd = [1,3,5]
print( (Odd +[2, 4, 6])[4] )
print( (Odd +[12, 14, 16])[4] - (Odd +[2, 4, 6])[4] )
Answer
Output
4
10
Explanation
Odd + [2, 4, 6] will return [1, 3, 5, 2, 4, 6]. The element at index 4 of this list
is 4 so the first output is 4. (Odd +[12, 14, 16])[4] is 14 and (Odd +[2, 4, 6])[4]
is 4. 14 - 4 = 10 which is the second output.
Output
1
2
[13, 18, 11, 16, 13, 18, 13, 3]
Explanation
List1.index(18) gives the first index of element 18 in List1 which in this case is
1. List1.count(18) returns how many times 18 appears in List1 which in this case is
2. List1.count(13) returns 3 as 13 appears 3 times in List1.
List1.append(List1.count(13)) add this 3 to the end of List1 so it becomes [13, 18,
11, 16, 13, 18, 13, 3].
L1 = [1, 3, 5, 7, 9]
print (L1 == L1.reverse( ) )
print (L1)
Answer
Output
False
[9, 7, 5, 3, 1]
Explanation
L1 is not equal to its reverse so L1 == L1.reverse( ) gives False but L1.reverse( )
reverses L1 in place so after that statement executes, L1 becomes [9, 7, 5, 3, 1].
L1 == L2
L1.upper( )
L1[3].upper( )
L2.upper( )
L2[1].upper( )
L2[1][1].upper( )
Answer
L1.upper( ) will cause an error as upper() method can be called with Strings not
Lists.
L2.upper( ) will cause an error as upper() method can be called with Strings not
Lists.
L2[1].upper( ) will cause an error as L2[1] is a list — [ "is", "another"] and
upper() method cannot be called on Lists.
From the previous question, give output of expressions that do not result in error.
Answer
Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88], which function can change
the list to:
L1.pop(4)
del L1[4:6]
del L1[:4]
What is the difference between following two expressions, if lst is given as [1, 3,
5]
Answer
(i)
lst * 3 will give [1, 3, 5, 1, 3, 5, 1, 3, 5] but the original lst will remains
unchanged, it will be [1, 3, 5] only.
lst *= 3 will also give [1, 3, 5, 1, 3, 5, 1, 3, 5] only but it will assign this
result back to lst so lst will be changed to [1, 3, 5, 1, 3, 5, 1, 3, 5].
(ii)
lst + 3 will cause an error as both operands of + operator should be of same type
but here one operand is list and the other integer.
lst += [3] will add 3 to the end of lst so lst becomes [1, 3, 5, 3].
Write a program to compare two equal sized lists and print the first index where
they differ.
Solution
print("Enter two equal sized lists")
l1 = eval(input("Enter first list: "))
l2 = eval(input("Enter second list: "))
for i in range(len(l1)):
if l1[i] != l2[i]:
print("Lists differ at index", i)
break;
else:
print("Lists are equal")
Output
Enter two equal sized lists
Enter first list: [80, 60, 50, 40, 30]
Enter second list: [80, 60, 55, 42, 30]
Lists differ at index 2
=====================================
Write a program to move all duplicate values in a list to the end of the list.
Solution
l = eval(input("Enter the list: "))
dedup = []
dup = []
for i in l:
if i in dedup:
dup.append(i)
else:
dedup.append(i)
l = dedup + dup
print("Modified List:")
print(l)
Output
Enter the list: [20, 15, 18, 15, 7, 18, 12, 13, 7]
Modified List:
[20, 15, 18, 7, 12, 13, 15, 18, 7]
Write a program to display the maximum and minimum values from the specified range
of indexes of list.
Solution
l = eval(input("Enter the list: "))
start = int(input("Enter start index: "))
stop = int(input("Enter stop index: "))
Write a program to read two lists num and denum which contain the numerators and
denominators of same fractions at the respective indexes. Then display the smallest
fraction along with its index.
Solution
num = eval(input("Enter numerators list: "))
denum = eval(input("Enter denominators list: "))
small = 0.0
smallIdx = 0
for i in range(len(num)):
t = num[i] / denum[i]
if t < small:
small = t
smallIdx = i
'''L is a list of numbers. Print a new list where each element is the corresponding
element of list L summed with number num.'''
Solution
l1 = eval(input("Enter list of numbers: "))
num = int(input("Enter the number to sum with (num): "))
l2 = []
for i in l1:
l2.append(i + num)
print("New list:")
print(l2)
Output
Enter list of numbers: [10, 20, 30, 40, 50]
Enter the number to sum with (num): 15
New list:
[25, 35, 45, 55, 65]
Solution
l = eval(input("Enter list of strings: "))
largeIdx = 0
largeLen = 0
for i in range(len(l)):
length = len(l[i])
if length > largeLen:
largeLen = length
largeIdx = i
Write a program that reads the n to display nth term of Fibonacci series.
The program prompts for element and prints out the value of that element of the
Fibonacci sequence.
Thus:
input 7, produces 13
input 9, produces 34
Hints:
A Don't try to just type out the entire list. It gets big very fast. Element 25 is
75205. Element 100 is 354224848179261915075. So keep upper limit of n to 20.
Solution
n = int(input("Enter n: "))
if (n > 20):
print("n should be less than or equal to 20")
else :
a = 0
b = 1
c = a + b
for i in range(3, n + 1):
a = b
b = c
c = a + b
=====================================
Enter n: 9
9 term of Fibonacci series = 34
=====================================
Enter n: 25
n should be less than or equal to 20
Write a program rotates the elements of a list so that the element at the first
index moves to the second index, the element in the second index moves to the third
index, etc., and the element in the last index moves to the first index.
Solution
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Output
Enter the list: [8, 10, 13, 25, 7, 11]
Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]
Write a program that takes any two lists L and M of the same size and adds their
elements together to form a new list N whose elements are sums of the corresponding
elements in L and M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N
should equal [4,6,13].
Solution
print("Enter two lists of same size")
L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)
Output
Enter two lists of same size
Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]
print("Created List:")
print(l)
Output
Created List:
['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', 'ggggggg', 'hhhhhhhh', 'iiiiiiiii',
'jjjjjjjjjj', 'kkkkkkkkkkk', 'llllllllllll', 'mmmmmmmmmmmmm', 'nnnnnnnnnnnnnn',
'ooooooooooooooo', 'pppppppppppppppp', 'qqqqqqqqqqqqqqqqq', 'rrrrrrrrrrrrrrrrrr',
'sssssssssssssssssss', 'tttttttttttttttttttt', 'uuuuuuuuuuuuuuuuuuuuu',
'vvvvvvvvvvvvvvvvvvvvvv', 'wwwwwwwwwwwwwwwwwwwwwww', 'xxxxxxxxxxxxxxxxxxxxxxxx',
'yyyyyyyyyyyyyyyyyyyyyyyyy', 'zzzzzzzzzzzzzzzzzzzzzzzzzz']
Write a program to check if a number is present in the list or not. If the number
is present, print the position of the number. Print an appropriate message if the
number is not present in the list.
Solution
l = eval(input("Enter list: "))
n = int(input("Enter number to search: "))
if n in l:
print(n, "found at index", l.index(n))
else :
print(n, "not found in list")
Output
Enter list: [1, 3, 15, 8, 20]
Enter number to search: 15
15 found at index 2
Ask the user to enter a list of strings. Create a new list that consists of those
strings with their first characters removed.
Solution
l1 = eval(input("Enter a list of strings: "))
l2 = []
for i in range(len(l1)):
l2.append(l1[i][1:])
Ask the user to enter a list containing numbers between 1 and 12. Then replace all
of the entries in the list that are greater than 10 with 10.
Solution
l = eval(input("Enter list having numbers between 1 & 12: "))
for i in range(len(l)):
if l[i] > 10:
l[i] = 10
Write a program that inputs two lists and creates a third, that contains all
elements of the first followed by all elements of the second.
Solution
l1 = eval(input("Enter first list: "))
l2 = eval(input("Enter second list: "))
l3 = l1 + l2
print("Joined List:", l3)
Output
Enter first list: [1, 2, 3, 4, 5]
Enter second list: [11, 12, 13, 14, 15]
Joined List: [1, 2, 3, 4, 5, 11, 12, 13, 14, 15]
Solution
l = eval(input("Enter a list: "))
print("Original list:", l)
l.reverse()
print("Reversed list:", l)
Output
Enter a list: [1, 2, 3, 4, 5]
Original list: [1, 2, 3, 4, 5]
Reversed list: [5, 4, 3, 2, 1]
Solution
lst = eval(input("Enter a list: "))
print("Existing list is:", lst)
for i in range(len(lst)):
lst[i] += n
Write a program that inputs two tuples seq_a and seq_b and prints True if every
element in seq_a is also an element of seq_b, else prints False.
Solution
seq_a = eval(input("Enter the first tuple: "))
seq_b = eval(input("Enter the second tuple: "))
for i in seq_a:
if i not in seq_b:
print("False")
break
else:
print("True")
Output
Enter the first tuple: 1,3,5
Enter the second tuple: 4,5,1,3
True
Given a tuple pairs = ((2, 5), (4, 2), (9, 8), (12, 10)), count the number of pairs
(a, b) such that both a and b are even.
Solution
tup = ((2,5),(4,2),(9,8),(12,10))
count = 0
tup_length = len(tup)
for i in range (tup_length):
if tup [i][0] % 2 == 0 and tup[i][1] % 2 == 0:
count = count + 1
print("The number of pair where both a and b are even:", count)
Output
The number of pair where both a and b are even: 2
Create a tuple containing the squares of the integers 1 through 50 using a for
loop.
Solution
tup = ()
for i in range(1,51):
tup = tup + (i**2,)
print("The square of integers from 1 to 50 is:" ,tup)
Output
The square of integers from 1 to 50 is: (1, 4, 9, 16, 25, 36, 49, 64, 81, 100,
121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676,
729, 784, 841, 900, 961, 1024, 1089, 1156, 1225, 1296, 1369, 1444, 1521, 1600,
1681, 1764, 1849, 1936, 2025, 2116, 2209, 2304, 2401, 2500)
Write a program that interactively creates a nested tuple to store the marks in
three subjects for five students and also add a function that computes total marks
and average marks obtained by each student.
Tuple will look somewhat like :
marks( (45, 45, 40), (35, 40, 38),(36, 30, 38), (25, 27, 20), (10, 15, 20) )
Solution
num_of_students = 5
tup = ()
def totalAndAvgMarks(x):
total_marks = sum(x)
avg_marks = total_marks / len(x)
return (total_marks, avg_marks)
for i in range(num_of_students):
print("Enter the marks of student", i + 1)
m1 = int(input("Enter marks in first subject: "))
m2 = int(input("Enter marks in second subject: "))
m3 = int(input("Enter marks in third subject: "))
tup = tup + ((m1, m2, m3),)
print()
for i in range(num_of_students):
print("The total marks of student", i + 1,"=", totalAndAvgMarks(tup[i])[0])
print("The average marks of student", i + 1,"=", totalAndAvgMarks(tup[i])[1])
print()
Output
Enter the marks of student 1
Enter marks in first subject: 25
Enter marks in second subject: 45
Enter marks in third subject: 45
Nested tuple of student data is: ((25, 45, 45), (90, 89, 95), (68, 70, 56), (23,
56, 45), (100, 98, 99))
The total marks of student 1 = 115
The average marks of student 1 = 38.333333333333336
Write a program that interactively creates a nested tuple to store the marks in
three subjects for five students, i.e., tuple will look somewhat like :
marks( (45, 45, 40), (35, 40, 38), (36, 30, 38), (25, 27, 20), (10, 15, 20) )
Solution
num_of_students = 5
tup = ()
for i in range(num_of_students):
print("Enter the marks of student", i + 1)
m1 = int(input("Enter marks in first subject: "))
m2 = int(input("Enter marks in second subject: "))
m3 = int(input("Enter marks in third subject: "))
tup = tup + ((m1, m2, m3),)
print()
Nested tuple of student data is: ((89, 78, 67), (56, 89, 55), (88, 78, 90), (78,
67,56), (45, 34, 23))
Write a program to create a nested tuple to store roll number, name and marks of
students.
Solution
tup = ()
ans = "y"
while ans == "y" or ans == "Y" :
roll_num = int(input("Enter roll number of student: "))
name = input("Enter name of student: ")
marks = int(input("Enter marks of student: "))
tup += ((roll_num, name, marks),)
ans = input("Do you want to enter more marks? (y/n): ")
print(tup)
Output
Enter roll number of student: 1
Enter name of student: Shreya Bansal
Enter marks of student: 85
Do you want to enter more marks? (y/n): y
Enter roll number of student: 2
Enter name of student: Nikhil Gupta
Enter marks of student: 78
Do you want to enter more marks? (y/n): y
Enter roll number of student: 3
Enter name of student: Avni Dixit
Enter marks of student: 96
Do you want to enter more marks? (y/n): n
((1, 'Shreya Bansal', 85), (2, 'Nikhil Gupta', 78), (3, 'Avni Dixit', 96))
Write a program that receives a Fibonacci term and returns a number telling which
term it is. For instance, if you pass 3, it returns 5, telling it is 5th term; for
8, it returns 7.
Solution
term = int(input ("Enter Fibonacci Term: "))
fib = (0,1)
fib_len = len(fib)
if term == 0:
print("0 is fibonacci term number 1")
elif term == 1:
print("1 is fibonacci term number 2")
elif fib[fib_len - 1] == term:
print(term, "is fibonacci term number", fib_len)
else:
print("The term", term , "does not exist in fibonacci series")
Output
Enter Fibonacci Term: 8
8 is fibonacci term number 7
Write a program that receives the index and returns the corresponding value.
Solution
tup = eval(input("Enter the elements of tuple:"))
b = int(eval(input("Enter the index value:")))
c = len(tup)
if b < c:
print("value of tuple at index", b ,"is:" ,tup[b])
else:
print("Index is out of range")
Output
Enter the elements of tuple: 1,2,3,4,5
Enter the index value: 3
value of tuple at index 3 is: 4
Write a Python program that creates a tuple storing first 9 terms of Fibonacci
series.
Solution
lst = [0,1]
a = 0
b = 1
c = 0
for i in range(7):
c = a + b
a = b
b = c
lst.append(c)
tup = tuple(lst)
Consider the following code and then answer the questions that follow :
Output
Dictionary contents
5 : number numbernumbernumber
a : string stringstringstring
x d1[x] d1[x] * 3
5 number numbernumbernumber
a string stringstringstring
(1,2) tuple tupletupletuple
d = dict()
d['left'] = '<'
d['right'] = '>'
d['end'] = ' '
print(d['left'] and d['right'] or d['right'] and d['left'])
print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])
print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])
print("end")
Answer
Output
>
>
end
Explanation
print(d['left'] and d['right'] or d['right'] and d['left'])
and operator has higher precedence than or so d['left'] and d['right'] and
d['right'] and d['left']) will be evaluated first.
d['left'] and d['right'] will return value of d['right'] i.e. '>' because first
operand of and operator is true so it will return the value of second operand.
Similarly, d['right'] and d['left']) will return value of d['left'] i.e. '<'.
Now the expression becomes '>' or '<'. This expression will evaluate to '>' as or
operator returns its first operand if the first operand is true. (or operator
returns its second operand only when its first operand is false). Thus, '>' gets
printed as the first line of the output.
print(d['left'] and d['right'] or d['right'] and d['left'] and d['end'])
and operator has higher precedence than or so d['left'] and d['right'] and
d['right'] and d['left'] and d['end'] will be evaluated first.
d['left'] and d['right'] will return value of d['right'] i.e. '>'.
d['right'] and d['left'] will return value of d['left'] i.e. '<'. d['right'] and
d['left'] and d['end'] becomes '<' and ' '. and operator returns its second operand
in this case so the expression evaluates to ' '.
Now the expression becomes '>' or ' '. or operator will return first operand in
this case. Thus, '>' gets printed as the second line of the output.
print((d['left'] and d['right'] or d['right'] and d['left']) and d['end'])
(d['left'] and d['right'] or d['right'] and d['left']) will be evaluated first as
it is enclosed in parentheses. From part 1, we know this expression will return
'>'.
Now the expression becomes '>' and d['end'] i.e., '>' and ' '. and operator returns
' ', its second argument as its first argument is true. Thus, ' ' gets printed as
the third line of the output.
text = "abracadabraaabbccrr"
counts = {}
ct = 0
lst = []
for word in text:
if word not in lst:
lst.append(word)
counts[word] = 0
ct = ct + 1
counts[word] = counts[word] + 1
print(counts)
print(lst)
Answer
Output
{'a': 7, 'b': 4, 'r': 4, 'c': 3, 'd': 1}
['a', 'b', 'r', 'c', 'd']
Explanation
This python program counts the frequency of each character in a string. Here is a
step-by-step explanation of the program:
Output
{2: 3, 3: 3, 5: 2, 1: 2}
{2: 6, 3: 9, 5: 10, 1: 2}
Explanation
This python program counts the frequency of each number in a list and then
multiplies each frequency by its corresponding number. Here is a step-by-step
explanation of the program:
text = "abracadbra"
counts = {}
for word in text :
counts[word] = counts[word] + 1
Answer
Output
KeyError: 'a'
Explanation
The line counts[word] = counts[word] + 1 will cause a KeyError because we are
trying to access a key word of an empty dictionary. As the key is not present in
dictionary counts, hence a KeyError is generated.
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[[4,2,1]] = 10
print(my_dict)
Answer
Output
TypeError: unhashable type: 'list'
Explanation
The line my_dict[[4,2,1]] = 10 is in error because a list is being used as a key of
the dictionary. Lists being mutable data types are not allowed as keys in a
dictionary.
fruit = {}
L1 = ['Apple', 'banana', 'apple']
for index in L1 :
if index in fruit:
fruit[index] += 1
else :
fruit[index] = 1
print(len(fruit))
print(fruit)
Answer
Output
3
{'Apple': 1, 'banana': 1, 'apple': 1}
Explanation
This python program counts the frequency of each fruit in a list and outputs the
number of unique fruits and their frequency. The program does not account for the
case sensitivity of the fruit names so "Apple" and "apple" are counted as separate
fruits. Here is a step-by-step explanation of the program:
arr = {}
arr[1] = 1
arr['1'] = 2
arr[1] += 1
sum = 0
for k in arr:
sum += arr[k]
print(sum)
Answer
Output
4
Explanation
This python program computes the sum of values of items in the dictionary.
The arr dictionary is created and initialized with two key-value pairs, arr[1] = 1
and arr['1'] = 2. After that, the value of arr[1] is incremented by 1. At this
point arr = {1: 2, '1': 2}.
The program iterates through each key k in the arr dictionary and adds the value
arr[k] to the sum variable.
Output
KeyError: ('a', 'b')
Explanation
a is a dictionary containing three key-value pairs.
a['a','b'] will throw an error since given key ('a','b') is not present in
dictionary a.
dct = {}
dct[1] = 1
dct ['1'] = 2
dct[1.0] = 4
sum = 0
for k in dct:
print(k, sum)
sum += dct[k]
print(sum)
Answer
Output
1 0
1 4
6
Explanation
This python program computes the sum of values of items in the dictionary. It also
demonstrates that dictionaries in Python can have both integer and string keys, but
the keys must be unique.
The keys 1 and '1' will be treated as two different keys as the former is a number
and the latter is a string. But the keys 1 and 1.0 are considered the same as both
represent number 1.
1. The dct dictionary is created and initialized with two key-value pairs, dct[1] =
1 and dct['1'] = 2.
2. After that, dct[1.0] = 4 updates the value of key 1 to 4 as the keys 1 and 1.0
are considered the same. At this point, dct = {1: 4, '1': 2}.
3. Loop through each key k in dct. Below table shows the loop iterations:
k dct[k] sum Iteration
1 4 0 + 4 = 4 Iteration 1
'1' 2 4 + 2 = 6 Iteration 2
4. The final value of the sum variable is printed to the console.
Dictionaries can be stored inside another dictionary as values and not as keys.
Here, d4 is storing the other dictionaries as keys which is not allowed because
dictionaries are mutable objects. That's why this code is raising error.
It can be corrected by using d1, d2, d3 as values of d4.
The corrected code is shown below:
The following code has two dictionaries with tuples as keys. While one of these
dictionaries being successfully created, the other is giving some error. Find out
which dictionary will be created successfully and which one will give error and
correct it :
dict1 will be created successfully because tuples are used as keys. As tuples are
immutable, therefore it won't give any error.
dict2 will give an error because the tuples used as keys of dict2 contain lists as
their elements. As lists are mutable, so they can't appear in keys of the
dictionary.
It can be corrected by removing list elements from the tuples as shown below:
dict2 = { (1,2) : [1,2], (3,4) : [3, 4]}
Solution
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1)
D2 = {}
for key in D1:
num = sum(D1[key])
D2[key] = num
print(D2)
Output
Enter a dictionary D1: {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
D1 = {'A': [1, 2, 3], 'B': [4, 5, 6]}
{'A': 6, 'B': 15}
d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}
Solution
d1 = eval(input("Enter a dictionary d1: "))
d2 = eval(input("Enter a dictionary d2: "))
Write a program that checks if two same values in a dictionary have different keys.
That is, for dictionary D1 = { 'a' : 10, 'b': 20, 'c' : 10}, the program should
print 2 keys have same values and for dictionary D2 = {'a' : 10, 'b' : 20, 'c' :
30} , the program should print No keys have same values.
Solution
D1 = eval(input("Enter a dictionary D1: "))
print("D1 =", D1)
val = tuple(D1.values())
seen = []
flag = True
for i in val:
if i not in seen:
seen.append(i)
count = val.count(i)
if count > 1:
print(count, "keys have same value of", i)
flag = False
if flag:
print("No keys have same values")
Output
Enter a dictionary D1: {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
D1 = {'a': 10, 'b': 20, 'c': 10, 'd': 40, 'e': 10, 'f': 20}
3 keys have same value of 10
2 keys have same value of 20
Given two dictionaries say D1 and D2. Write a program that lists the overlapping
keys of the two dictionaries, i.e., if a key of D1 is also a key of D2, then list
it.
Solution
d1 = eval(input("Enter first dictionary: "))
d2 = eval(input("Enter second dictionary: "))
Solution
x = { "k1" : "v1" , "k2" : "v2", "k3" : "v3"}
inverted_x = {}
for i in x :
inverted_x[x[i]] = i
print(inverted_x)
Can you store the details of 10 students in a dictionary at the same time ? Details
include - rollno, name, marks, grade etc. Give example to support your answer.
Solution
n = 10
details = {}
for i in range(n):
name = input("Enter the name of student: ")
roll_num = int(input("Enter the roll number of student: "))
marks = int(input("Enter the marks of student: "))
grade = input("Enter the grade of student: ")
details[roll_num] = [name, marks, grade]
print()
print(details)
Create a dictionary whose keys are month names and whose values are the number of
days in the corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell how many days
are in the month.
(d) Print out the (key-value) pairs sorted by the number of days in each month.
Solution
days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
Write a program that repeatedly asks the user to enter product names and prices.
Store all of these in a dictionary whose keys are the product names and whose
values are the prices.
When the user is done entering products and prices, allow them to repeatedly enter
a product name and print the corresponding price or a message if the product is not
in the dictionary.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name: ")
p_price = float(input("Enter product price: "))
d[p_name] = p_price
ans = input("Do you want to enter more product names? (y/n): ")
ans = "y"
while ans == "y" or ans == "Y" :
p_name = input("Enter the product name to search: ")
print("Price:", d.get(p_name, "Product not found"))
ans = input("Do you want to know price of more products? (y/n): ")
Repeatedly ask the user to enter a team name and how many games the team has won
and how many they lost. Store this information in a dictionary where the keys are
the team names and the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a team name and
print out the team's winning percentage.
(b) Using the dictionary, create a list whose entries are the number of wins of
each team.
(c) Using the dictionary, create a list of all those teams that have winning
records.
Repeatedly ask the user to enter a team name and how many games the team has won
and how many they lost. Store this information in a dictionary where the keys are
the team names and the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a team name and
print out the team's winning percentage.
(b) Using the dictionary, create a list whose entries are the number of wins of
each team.
(c) Using the dictionary, create a list of all those teams that have winning
records.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter Team name: ")
w = int(input("Enter number of wins: "))
l = int(input("Enter number of losses: "))
d[name] = [w, l]
ans = input("Do you want to enter more team names? (y/n): ")
w_team = []
for i in d.values():
w_team.append(i[0])
w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)
Write a program to convert a number entered by the user into its corresponding
number in words. For example, if the input is 876 then the output should be 'Eight
Seven Six'.
(Hint. use dictionary for keys 0-9 and their values as equivalent words.)
Write a program to convert a number entered by the user into its corresponding
number in words. For example, if the input is 876 then the output should be 'Eight
Seven Six'.
(Hint. use dictionary for keys 0-9 and their values as equivalent words.)
Solution
num = int(input("Enter a number: "))
d = {0 : "Zero" , 1 : "One" , 2 : "Two" , 3 : "Three" , 4 : "Four" , 5 : "Five" , 6
: "Six" , 7 : "Seven" , 8 : "Eight" , 9 : "Nine"}
digit = 0
str = ""
while num > 0:
digit = num % 10
num = num // 10
str = d[digit] + " " + str
print(str)
Solution
m = []
n = int(input("Enter the number of elements in list: "))
for i in range(n):
element = input("Enter an element to add to the list: ")
m.append(element)
print("List before deletion:", m)
e = input("Enter the element to delete from the list: ")
m.remove(e)
print("List after deletion:", m)
Write a program to enter names of employees and their salaries as input and store
them in a dictionary.
Solution
d = {}
ans = "y"
while ans == "y" or ans == "Y" :
name = input("Enter employee name: ")
sal = float(input("Enter employee salary: "))
d[name] = sal
ans = input("Do you want to enter more employee names? (y/n)")
print(d)
Write a program to count the number of times a character appears in a given string.
Solution
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)
Write a program that uses a while loop to add up all the even numbers between 100
and 200.
Output
10.0$20
10.0$2.0###
Explanation
The code snippet provided defines a function Changer that takes two parameters P
and Q, where Q is assigned a default value of 10. Inside the function, P is divided
by Q and P is assigned the quotient, and then Q is assigned the remainder of P
divided by Q. The modified P value is returned from the function. In the main code,
variables A and B are initialized with values 200 and 20, respectively. The Changer
function is called first with A and B as arguments, modifying the value of A. The
updated values of A and B are then printed with a separator of '$'. Next, the
Changer function is called again with only B as an argument, updating B. Finally,
the updated values of A and B are printed again with a separator of '$' and an end
marker of '###'.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------Explain differences between pop(),remove() and discard()
functionsin Set
write a program that receives 3 sets of values of p, n, and r and calculates simple
interest for each
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------Name the three ways of creating a dictionary in Python?
Output
Jay
Finished!
Riya
Finished!
Tanu
Got it!
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
Create a class called library with data attributes like acc_number, publisher,
title and author. The methods of the class should include
a. read() -acc_number, title, author.
b. compute() - to accept the number of days late, calculate and display the fine
charged at the rate of $1.50 per day.
c. display the data.
How many times will the following for loop execute and what's the output?
for i in range(1,3,1):
for j in range(i+1):
print('*')
Answer
Loop executes for 5 times.
Output
*
*
*
*
*
Explanation
range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1]
so inner loop executes twice. For second iteration of outer loop j is in range [0,
1, 2] so inner loop executes 3 times. This makes the total number of loop
executions as 2 + 3 = 5.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
What are the three ways in which you can access the elements in the list in python.
Write program to exchange the values of two numbers with and without using
temporary variables.
How many times will the following for loop execute and what's the output?
The loops execute 0 times and the code produces no output. range(-1, 7, -2) returns
an empty sequence as there are no numbers that start at -1 and go till 6
decrementing by -2. Due to empty sequence, the loops don't execute.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
3 differences between remove() and pop() of list.
Write a program that accepts a string from the user and display the same string
after removing vowels from it.
Output
apple
PEAR
PEACH
grapefruit
Explanation
x.split(', ') breaks up string x into a list of strings so y becomes ['apple',
'pear', 'peach', 'grapefruit']. The for loop iterates over this list. apple and
grapefruit are less than m (since a and g comes before m) so they are converted to
lowercase and printed whereas pear and peach are converted to uppercase and
printed.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
Write a program that creates a list of 10 integers. Then create two lists by name
odd_list and even_list that have all odd and even values of the list respectively.
Output
o t
n w
e o
Explanation
Inside the while loop, each letter of x and y is accessed one by one and printed.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
What are the three ways in which you can access the elements in the tuples in
python.
Write a program that has the dictionary of your friends names as keys and phone
numbers as its values. Print the dictionary in a sorted order. Prompt the user to
enter the name and check if it is present in the dictionary. If the name is not
present,then enter the details in the dictionary.
x = [1,2,3]
counter = 0
while counter < len(x):
print(x[counter] * '%')
for y in x:
print(y * '* ')
counter += 1
Answer
Output
%
*
* *
* * *
%%
*
* *
* * *
%%%
*
* *
* * *
Explanation
In this code, the for loop is nested inside the while loop. Outer while loop runs 3
times and prints % as per the elements in x in each iteration. For each iteration
of while loop, the inner for loop executes 3 times printing * as per the elements
in x.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
Create a time-based application to wish the end user.For example, if the time is 6
a.m., display 'Good morning.'If the time is 6:45 p.m., show 'Good Evening.'
c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)
Answer
Output
50
Explanation
Outer loop executes 10 times. For each iteration of outer loop, inner loop executes
5 times. Thus, the statement c += 1 is executed 10 * 5 = 50 times. c is incremented
by 1 in each execution so final value of c becomes 50.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------
Write a program to accept some string from the keyboard and display its characters
by index wise(both positive and nEgative index)
x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer
Explanation
The x-y * 2 in range(x-y * 2) is evaluated as below:
x - y * 2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒ 0
Write a program to take a tuple of numbers from the keyboard and print its sum and
average
Output
-500
-400
-300
-200
-100
0
100
200
300
400
Explanation
range(-500, 500, 100) generates a sequence of numbers from -500 to 400 with each
subsequent number incrementing by 100. Each number of this sequence is assigned to
z one by one and then z gets printed inside the for loop.
Write a program to print different vowels present in the given word.Enter word to
search for vowels: amol.The different vowel present in amol are {'a', 'o'}
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print(sum)
print(my_dict)
Answer
Output
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
Write a program to take dictionary from the keyboard and print the sum of values
Answer
Output
True
Explanation
In the given python code snippet, id1 and id2 will point to two different objects
in memory as del rec deleted the original dictionary whose id is stored in id1 and
created a new dictionary with the same contents storing its id in id2. However, id1
== id2 will compare the contents of the two dictionaries pointed to by id1 and id2.
As contents of both the dictionaries are same hence it returns True. If in this
code we add another line print(id1 is id2) then this line will print False as id1
and id2 point to two different dictionary objects in memory.
Write a program to find number of occurrences of each letter present in the given
string
Output
1 #
1 # 2 #
1 # 2 # 3 #
Explanation
Numbers is a list containing the numbers 9, 18, 27, and 36.
The outer for loop iterates over each element in the list Numbers.
The inner loop iterates over the range from 1 to the remainder of Num divided by 8.
For example, if Num is 9, the range will be from 1 to 1 (9 % 8 = 1). If Num is 18,
the range will be from 1 to 2 (18 % 8 = 2), and so on. Then it prints the value of
N, followed by a "#", and ensures that the output is printed on the same line by
setting end=" ".
After both loops, it prints an empty line, effectively adding a newline character
to the output.
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = "")
Answer
Output
234566
Explanation
arr is initialised as a list with elements [1, 2, 3, 4, 5, 6].
for loop iterates over the indices from 1 to 5. For each index i, it assigns the
value of arr[i] to arr[i - 1], effectively shifting each element one position to
the left. After this loop, the list arr becomes [2, 3, 4, 5, 6, 6].
Second for loop iterates over the indices from 0 to 5 and prints each element of
the list arr without newline characters because of end="" parameter. Then it prints
the elements of the modified list arr, resulting in 234566.
Write a Python program to input 'n' classes and names of their class teachers to
store it in a dictionary and display the same. Also, accept a particular class from
the user and display the name of the class teacher of that class.
Write a program to store students' names and their percentage in a dictionary, and
delete a particular student name from the dictionary. Also display dictionary after
deletion.
Write a Python program to input names of 'n' customers and their details like items
bought, cost and phone number, store it in a dictionary and display all the details
in a tabular form.
Write a program to input your friends' names and their phone numbers and store them
in a dictionary as the key-value pair. Perform the following operations on the
dictionary:
(a) Display the Name and Phone numbers of all your friends.
(b) Add a new key-value pair in this dictionary and display the modified
dictionary.
(c) Delete a particular friend from the dictionary.
(d) Modify the phone number of an existing friend.
(e) Check if a friend is present in the dictionary or not.
(f) Display the dictionary in sorted order of names.
Write a program that prompts the user for product names and prices, and store these
key-value pairs in a dictionary where names are the keys and prices are the values.
Also, write a code to search for a product in a dictionary and display its price.
If the product is not there in the dictionary, then display the relevant message.
Write a Python program that accepts a value and checks whether the inputted value
is part of the given dictionary or not. If it is present, check for the frequency
of its occurrence and print the corresponding key, otherwise print an error
message.
Write a program to find the largest and the second largest elements in a given list
of elements.
Write a program to read a list of elements. Modify this list so that it does not
contain any duplicate elements, i.e., all elements occurring multiple times in the
list should appear only once.
Write a program to create a list of elements. Input an element from the user that
has to be inserted in the list. Also, input the position at which it is to be
inserted.
Write a program that accepts elements of a list S and adds all the odd values and
displays the sum.
WAP to multiply an element by 2 if it is odd index for a given list containing both
numbers and strings.
WAP to shift elements of a list so that first element moves to the second index and
second index moves to the third index, etc., and last element shifts to the first
position.
Write a program that inputs a list, replicates it twice and then prints the sorted
list in ascending and descending orders.
Write a program to create a dictionary with the roll number, name and marks of n
students in a class, and display the names of students who have secured marks above
75.
Write a Python program to input 'n' classes and names of their class teachers to
store it in a dictionary and display the same. Also, accept a particular class from
the user and display the name of the class teacher of that class.
Write a program to store students' names and their percentage in a dictionary, and
delete a particular student name from the dictionary. Also display dictionary after
deletion.
Write a program that reads a line, then counts how many times the word 'is' appears
in the line and displays the count.
Write a program to read three numbers in three variables and swap first two
variables with the sums of first and second, second and third numbers respectively.
Write a program to input a single digit(n) and print a 3 digit number created as
<n(n + 1)(n + 2)> e.g., if you input 7, then it should print 789. Assume that the
input digit is in range 1-7.
Write a program to input a line of text and print the biggest word (length wise)
from it.
Write a program to check if a number is present in the list or not. If the number
is present, print the position of the number. Print an appropriate message if the
number is not present in the list.
Write a program that takes any two lists L and M of the same size and adds their
elements together to form a new list N whose elements are sums of the corresponding
elements in L and M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N
should equal [4,6,13].
Write a Python program that creates a tuple storing first 9 terms of Fibonacci
series.
Create a tuple containing the squares of the integers 1 through 50 using a for
loop.
Given a tuple pairs = ((2, 5), (4, 2), (9, 8), (12, 10)), count the number of pairs
(a, b) such that both a and b are even.
Write a program to convert a number entered by the user into its corresponding
number in words. For example, if the input is 876 then the output should be 'Eight
Seven Six'.(Hint. use dictionary for keys 0-9 and their values as equivalent
words.)
A = 200
B = 20
A = Changer(A, B)
print(A, B, sep = '$')
B = Changer(B)
print(A, B, sep = '$', end = '###')
Answer
Output
10.0$20
10.0$2.0###
Explanation
The code snippet provided defines a function Changer that takes two parameters P
and Q, where Q is assigned a default value of 10. Inside the function, P is divided
by Q and P is assigned the quotient, and then Q is assigned the remainder of P
divided by Q. The modified P value is returned from the function. In the main code,
variables A and B are initialized with values 200 and 20, respectively. The Changer
function is called first with A and B as arguments, modifying the value of A. The
updated values of A and B are then printed with a separator of '$'. Next, the
Changer function is called again with only B as an argument, updating B. Finally,
the updated values of A and B are printed again with a separator of '$' and an end
marker of '###'.
S = "LOST"
L = [10, 21, 33, 4]
D = {}
for I in range(len(S)):
if I % 2 == 0:
D[L.pop()] = S[I]
else:
D[L.pop()] = I + 3
for K, V in D.items():
print(K, V, sep = "*")
Answer
Output
4*L
33*4
21*S
10*6
Explanation
The code initializes variables S, L, and D, representing a string, list, and
dictionary, respectively. The code iterates through the indices of string S. If the
index is even, it assigns the popped element from list L as a key in dictionary D
with the corresponding character from S as its value. If the index is odd, it
assigns the popped element from L as a key in D with the value being the index plus
3. This process continues until the loop ends. After the loop, it prints each key-
value pair from D, with keys and values separated by "*".
Output
Jay
Finished!
Riya
Finished!
Tanu
Got it!
How many times will the following for loop execute and what's the output?
for i in range(1,3,1):
for j in range(i+1):
print('*')
Answer
Output
*
*
*
*
*
Explanation
range(1,3,1) returns [1, 2]. For first iteration of outer loop j is in range [0, 1]
so inner loop executes twice. For second iteration of outer loop j is in range [0,
1, 2] so inner loop executes 3 times. This makes the total number of loop
executions as 2 + 3 = 5.
How many times will the following for loop execute and what's the output?
The loops execute 0 times and the code produces no output. range(-1, 7, -2) returns
an empty sequence as there are no numbers that start at -1 and go till 6
decrementing by -2. Due to empty sequence, the loops don't execute.
Output
apple
PEAR
PEACH
grapefruit
Explanation
x.split(', ') breaks up string x into a list of strings so y becomes ['apple',
'pear', 'peach', 'grapefruit']. The for loop iterates over this list. apple and
grapefruit are less than m (since a and g comes before m) so they are converted to
lowercase and printed whereas pear and peach are converted to uppercase and
printed.
x = 'one'
y = 'two'
counter = 0
while counter < len(x):
print(x[counter], y[counter])
counter += 1
Answer
Output
o t
n w
e o
Explanation
Inside the while loop, each letter of x and y is accessed one by one and printed.
Predict the output of the following code fragments:
x = [1,2,3]
counter = 0
while counter < len(x):
print(x[counter] * '%')
for y in x:
print(y * '* ')
counter += 1
Answer
Output
%
*
* *
* * *
%%
*
* *
* * *
%%%
*
* *
* * *
Explanation
In this code, the for loop is nested inside the while loop. Outer while loop runs 3
times and prints % as per the elements in x in each iteration. For each iteration
of while loop, the inner for loop executes 3 times printing * as per the elements
in x.
c = 0
for x in range(10):
for y in range(5):
c += 1
print (c)
Answer
Output
50
Explanation
Outer loop executes 10 times. For each iteration of outer loop, inner loop executes
5 times. Thus, the statement c += 1 is executed 10 * 5 = 50 times. c is incremented
by 1 in each execution so final value of c becomes 50.
x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer
Explanation
The x-y * 2 in range(x-y * 2) is evaluated as below:
x - y * 2
⇒ 10 - 5 * 2
⇒ 10 - 10 [∵ * has higher precedence than -]
⇒ 0
Output
-500
-400
-300
-200
-100
0
100
200
300
400
Explanation
range(-500, 500, 100) generates a sequence of numbers from -500 to 400 with each
subsequent number incrementing by 100. Each number of this sequence is assigned to
z one by one and then z gets printed inside the for loop.
Write a program that creates a list of all the integers less than 100 that are
multiples of 3 or 5.
my_dict = {}
my_dict[(1,2,4)] = 8
my_dict[(4,2,1)] = 10
my_dict[(1,2)] = 12
sum = 0
for k in my_dict:
sum += my_dict[k]
print(sum)
print(my_dict)
Answer
Output
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
Answer
Output
True
Explanation
In the given python code snippet, id1 and id2 will point to two different objects
in memory as del rec deleted the original dictionary whose id is stored in id1 and
created a new dictionary with the same contents storing its id in id2. However, id1
== id2 will compare the contents of the two dictionaries pointed to by id1 and id2.
As contents of both the dictionaries are same hence it returns True. If in this
code we add another line print(id1 is id2) then this line will print False as id1
and id2 point to two different dictionary objects in memory.
Output
1 #
1 # 2 #
1 # 2 # 3 #
Explanation
Numbers is a list containing the numbers 9, 18, 27, and 36.
The outer for loop iterates over each element in the list Numbers.
The inner loop iterates over the range from 1 to the remainder of Num divided by 8.
For example, if Num is 9, the range will be from 1 to 1 (9 % 8 = 1). If Num is 18,
the range will be from 1 to 2 (18 % 8 = 2), and so on. Then it prints the value of
N, followed by a "#", and ensures that the output is printed on the same line by
setting end=" ".
After both loops, it prints an empty line, effectively adding a newline character
to the output.
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = "")
Answer
Output
234566
Explanation
arr is initialised as a list with elements [1, 2, 3, 4, 5, 6].
for loop iterates over the indices from 1 to 5. For each index i, it assigns the
value of arr[i] to arr[i - 1], effectively shifting each element one position to
the left. After this loop, the list arr becomes [2, 3, 4, 5, 6, 6].
Second for loop iterates over the indices from 0 to 5 and prints each element of
the list arr without newline characters because of end="" parameter. Then it prints
the elements of the modified list arr, resulting in 234566.
Suppose we have a list of names and we want to create a dictionary using dictionary
comprehension where the names are the keys and their lengths are the values.
Output:
{'Alice': 5, 'Bob': 3, 'Saanvi': 6, 'Mahika': 6}
# This statement creates a dictionary from two lists containing first lists as keys
and second list as values.
combined_dict = {key: value for key, value in zip(keys, values)}
print(combined_dict)
Let us consider a scenario where we have a dictionary for some product prices. We
want to apply a discount of 20% to all the prices of products. Look at the example
code below for it.
Let’s look at a program in which we will find all numbers between 1 to 30 divisible
by 2 and 5.
suppose we have a list that contains other lists as elements, we want to transform
it into a single-dimensional list. We can achieve this is by using list
comprehension in Python. Let’s take a very simple example on it.
# take list
my_list = [1, 7, 8, 1, 5]
**Scenario:**
**Task:**
Use list comprehension to create a new list containing only the order amounts for
orders placed in the last 30 days.
**Solution:**
```python
from datetime import datetime, timedelta
print(recent_order_amounts)
```
**Explanation:**
2. **Sample data:**
- `orders`: A list of dictionaries, each representing an order.
4. **List comprehension:**
- `order['order_amount']`: Extract the order amount from each order dictionary.
- `for order in orders`: Iterate through the list of orders.
- `if datetime.strptime(order['order_date'], '%Y-%m-%d') >= thirty_days_ago`:
- Convert the order date string to a datetime object.
- Check if the order date is within the last 30 days.
This example demonstrates how list comprehension can be used to efficiently filter
data and extract specific values based on conditions. You can adapt this approach
to various scenarios in your e-commerce analysis, such as calculating total sales
within a specific time frame, identifying high-value customers, or analyzing order
trends.
**Scenario:**
* **Task:**
* Create a new list containing only the order IDs for orders placed by
customers with IDs greater than 1000.
* Use list comprehension to solve this efficiently.
**Example:**
```python
orders = [
(100, 'ORD123', 150.00),
(1200, 'ORD456', 200.00),
(500, 'ORD789', 100.00),
(1500, 'ORD101', 300.00),
(800, 'ORD111', 120.00)
]
**Explanation:**
1. **Initialization:**
- `orders`: A list of tuples, where each tuple represents an order with customer
ID, order ID, and order amount.
2. **List Comprehension:**
- `[order_id for customer_id, order_id, amount in orders if customer_id >
1000]`:
- Iterates through each `order` (which is a tuple) in the `orders` list.
- Unpacks the tuple into `customer_id`, `order_id`, and `amount`.
- Includes the `order_id` in the new list only if the `customer_id` is greater
than 1000.
3. **Output:**
- The `high_value_orders` list contains only the order IDs for orders placed by
customers with IDs greater than 1000.
This example demonstrates how list comprehension provides a concise and efficient
way to filter and extract specific data from a list of tuples.
**Further Considerations:**
- You could extend this scenario to filter orders based on other criteria, such as
order amount, order date, or customer location.
- List comprehensions can be used with nested loops to process more complex data
structures.
I hope this scenario and example help you understand the practical applications of
list comprehensions in Python!
Imagine you're a data analyst working for an e-commerce company. You have a list of
customer orders, each represented as a dictionary with keys like "customer_id",
"order_date", "total_amount", and "items". You need to quickly analyze this data to
identify high-value customers and potential trends.
Question:
Popular Items: Write a list comprehension to create a list of unique item names
that appear in more than 5 orders.
Python
orders = [
{'customer_id': 1, 'order_date': '2023-11-15', 'total_amount': 1200, 'items':
['item1', 'item2']},
{'customer_id': 2, 'order_date': '2023-12-20', 'total_amount': 500, 'items':
['item3']},
{'customer_id': 1, 'order_date': '2024-01-10', 'total_amount': 800, 'items':
['item1', 'item4']},
{'customer_id': 3, 'order_date': '2024-02-05', 'total_amount': 1500, 'items':
['item2', 'item5']}
]
The list comprehension iterates through each order in the orders list.
The if condition checks if the total_amount of the order is greater than $1000.
If the condition is true, the customer_id of that order is added to the
high_value_customers list.
Challenge:
Can you modify the list comprehension in Question 1 to also include the order date
for each high-value customer?
**Scenario:**
**Question:**
1. **High-Value Customers:**
- Write a list comprehension to create a list of customer IDs for all customers
who have made at least 3 orders with a total amount greater than $100.
3. **Popular Products:**
- Write a list comprehension to create a list of all unique product names that
appear in any order.
```python
orders = [
{"customer_id": 1, "order_date": "2024-07-05", "total_amount": 150, "items":
["Laptop", "Mouse"]},
{"customer_id": 2, "order_date": "2024-06-20", "total_amount": 80, "items":
["Phone Case"]},
{"customer_id": 1, "order_date": "2024-08-10", "total_amount": 120, "items":
["Headphones"]},
{"customer_id": 3, "order_date": "2024-07-15", "total_amount": 50, "items":
["Book"]},
{"customer_id": 1, "order_date": "2024-05-02", "total_amount": 180, "items":
["Tablet"]},
{"customer_id": 2, "order_date": "2024-07-28", "total_amount": 110, "items":
["Watch"]}
]
```
**Solutions:**
1. **High-Value Customers:**
```python
high_value_customers = [order["customer_id"]
for order in orders
if order["total_amount"] > 100]
```
2. **Orders in July:**
```python
july_orders = [order["order_date"]
for order in orders
if order["order_date"].startswith("2024-07")]
```
3. **Popular Products:**
```python
popular_products = list(set([item
for order in orders
for item in order["items"]]))
```
**Explanation:**
This scenario demonstrates the power of list comprehensions for efficient data
analysis. By using concise and expressive syntax, you can quickly extract valuable
insights from your data.
**Scenario:**
**Task:**
Use list comprehension to create a new list containing only the order amounts for
orders placed in the last month.
**Example Data:**
```python
orders = [
(1, 100, '2024-11-15'),
(2, 50, '2024-12-01'),
(3, 150, '2024-11-28'),
(4, 75, '2024-12-10'),
(5, 200, '2024-11-30')
]
**Solution:**
```python
from datetime import datetime, timedelta
today = datetime.now()
last_month_start = today - timedelta(days=30)
recent_orders = [
order_amount
for customer_id, order_amount, order_date in orders
if datetime.strptime(order_date, '%Y-%m-%d') >= last_month_start
]
**Explanation:**
2. **Calculate `last_month_start`:**
- `today`: Get the current date and time.
- `timedelta(days=30)`: Create a time difference of 30 days.
- `last_month_start`: Subtract 30 days from `today` to get the start date of the
last month.
3. **List Comprehension:**
- `for customer_id, order_amount, order_date in orders`: Iterate through each
order tuple.
- `datetime.strptime(order_date, '%Y-%m-%d')`: Convert the `order_date` string
to a datetime object.
- `if datetime.strptime(order_date, '%Y-%m-%d') >= last_month_start`: Filter
orders placed on or after the start of the last month.
- `order_amount`: Include only the `order_amount` in the new list.
This concise list comprehension effectively filters the orders and extracts the
relevant information, demonstrating the power of this technique for data
manipulation.
**Scenario:**
Imagine you're an analyst at an e-commerce company. You have a list of customer
orders, each represented as a dictionary with keys like "customer_id",
"order_date", "total_amount", and "items". You need to quickly analyze this data to
identify high-value customers and potential trends.
**Question:**
**Solution:**
```python
orders = [
{'customer_id': 1, 'order_date': '2024-07-05', 'total_amount': 150, 'items':
['laptop', 'mouse']},
{'customer_id': 2, 'order_date': '2024-07-08', 'total_amount': 50, 'items':
['phone', 'charger']},
{'customer_id': 1, 'order_date': '2024-07-10', 'total_amount': 80, 'items':
['headphones']},
{'customer_id': 3, 'order_date': '2024-07-12', 'total_amount': 200, 'items':
['tablet', 'keyboard']}
]
# 2. Create a list of customer IDs who made orders with a total amount greater than
$100
high_value_customers = [order['customer_id'] for order in orders if
order['total_amount'] > 100]
print("High-Value Customers:", high_value_customers)
**Explanation:**
* **Order Dates:**
- The first list comprehension iterates through each `order` in the `orders`
list.
- For each `order`, it extracts the `order_date` and adds it to the
`order_dates` list.
* **High-Value Customers:**
- The second list comprehension iterates through each `order`.
- It includes the `customer_id` in the `high_value_customers` list only if the
`order['total_amount']` is greater than 100.
* **Unique Items:**
- This is a nested list comprehension.
- The outer loop iterates through each `order`.
- The inner loop iterates through each `item` in the `order['items']` list.
- All items are extracted and then converted to a set to remove duplicates.
- Finally, the set is converted back to a list.
This demonstrates how list comprehension can efficiently process data and generate
the desired information in a concise and readable way.
**Scenario:**
**Challenge:**
Use list comprehension to create a list of customer IDs who meet the following
criteria:
**Example Data:**
```python
orders = [
{"customer_id": 1, "order_amount": 100, "order_date": "2024-11-15"},
{"customer_id": 2, "order_amount": 50, "order_date": "2024-11-20"},
{"customer_id": 1, "order_amount": 80, "order_date": "2024-11-25"},
{"customer_id": 3, "order_amount": 120, "order_date": "2024-10-10"},
{"customer_id": 2, "order_amount": 75, "order_date": "2024-11-18"},
]
```
**Solution:**
```python
from datetime import datetime, timedelta
today = datetime.now()
thirty_days_ago = today - timedelta(days=30)
repeat_customers = {
customer_id
for order in orders
if order["order_date"] >= thirty_days_ago.strftime("%Y-%m-%d")
for customer_id in [order["customer_id"]]
if orders.count({"customer_id": customer_id}) > 1
}
**Explanation:**
3. **List comprehension:**
- `for order in orders`: Iterates through each order in the `orders` list.
- `if order["order_date"] >= thirty_days_ago.strftime("%Y-%m-%d")`: Filters
orders placed within the last 30 days.
- `for customer_id in [order["customer_id"]]`: Extracts the `customer_id` from
the current order.
- `if orders.count({"customer_id": customer_id}) > 1`: Checks if the
`customer_id` has more than one order in the list.
This list comprehension effectively identifies customers who have made multiple
orders within the last 30 days, providing valuable insights for targeted marketing
campaigns or customer loyalty programs.
**Scenario:**
You are developing a game where players collect unique items. Each player has an
inventory represented as a list of item names. You need to implement a function
that determines if a player can successfully craft a specific item based on the
items currently in their inventory.
**Challenge:**
2. Returns `True` if the player has all the required items in their inventory, and
`False` otherwise.
**Example Usage:**
```python
player_inventory = ["wood", "stone", "iron"]
required_items = ["wood", "stone"]
**Solution:**
```python
def can_craft(player_inventory, required_items):
"""
Checks if a player can craft an item based on their inventory.
Args:
player_inventory: A list of strings representing the player's inventory.
required_items: A list of strings representing the items required to craft the
item.
Returns:
True if the player has all the required items, False otherwise.
"""
for item in required_items:
if item not in player_inventory:
return False
return True
```
**Explanation:**
1. **Function Definition:**
- The function `can_craft` takes two arguments: `player_inventory` and
`required_items`.
This function effectively determines whether a player can craft a specific item
based on the items they currently possess in their inventory. This is a fundamental
concept in game development and can be extended to handle more complex crafting
systems with varying item quantities and crafting recipes.
Scenario:
You are developing a simple text-based game where players can collect items. Each
item has a name and a weight. You need to keep track of the player's inventory,
which is represented as a list of dictionaries, where each dictionary holds the
item's name and weight.
1. Create an empty inventory list.
2. Implement a function `add_item(inventory, item_name, item_weight)` that adds a
new item to the player's inventory.
3. Implement a function `remove_item(inventory, item_name)` that removes a specific
item from the player's inventory.
4. Implement a function `get_total_weight(inventory)` that calculates the total
weight of all items in the inventory.
5. Implement a function `display_inventory(inventory)` that prints a nicely
formatted list of items in the inventory.
Example Usage:
inventory = []
add_item(inventory, "Sword", 5)
add_item(inventory, "Shield", 10)
add_item(inventory, "Potion", 1)
remove_item(inventory, "Shield")
print("Total weight:", get_total_weight(inventory))
display_inventory(inventory)
Expected Output:
Total weight: 6
Inventory:
- Sword (5 kg)
- Potion (1 kg)
Solution:
def get_total_weight(inventory):
"""Calculates the total weight of all items in the inventory."""
total_weight = 0
for item in inventory:
total_weight += item["weight"]
return total_weight
def display_inventory(inventory):
"""Prints a nicely formatted list of items in the inventory."""
print("Inventory:")
for item in inventory:
print(f" - {item['name']} ({item['weight']} kg)")
# Example Usage
inventory = []
add_item(inventory, "Sword", 5)
add_item(inventory, "Shield", 10)
add_item(inventory, "Potion", 1)
remove_item(inventory, "Shield")
This solution demonstrates how to use lists in Python to manage the player's
inventory in a simple game. It covers basic list operations like appending,
removing, and iterating through the list.
Scenario:
You are developing a game where players collect unique items. Each player has an
inventory represented as a list of item names. You need to implement a function
that allows players to combine their inventories, ensuring that no duplicate items
are included in the combined inventory.Write a Python function
`combine_inventories(inventory1, inventory2)` that takes two lists representing
player inventories as input and returns a new list containing all unique items from
both inventories.
Example:
**Solution:**
```python
def combine_inventories(inventory1, inventory2):
"""
Combines two player inventories, removing duplicate items.
Args:
inventory1: A list of items in the first inventory.
inventory2: A list of items in the second inventory.
Returns:
A new list containing all unique items from both inventories.
"""
combined_inventory = inventory1 + inventory2
return list(set(combined_inventory))
# Example usage
inventory1 = ["Sword", "Shield", "Potion"]
inventory2 = ["Shield", "Bow", "Arrow"]
**Explanation:**
1. **Function Definition:**
- `combine_inventories(inventory1, inventory2)`: Defines a function that takes
two lists (`inventory1` and `inventory2`) as input.
2. **Combine Inventories:**
- `combined_inventory = inventory1 + inventory2`: Creates a new list by
combining the elements of both input lists.
3. **Remove Duplicates:**
- `list(set(combined_inventory))`:
- Converts the combined list into a set. A set in Python automatically
removes duplicate elements.
- Converts the set back into a list to maintain the original data structure.
This function efficiently combines the two inventories while ensuring that no
duplicate items are included in the final result.
Scenario:
You are developing a game where players collect unique items. Each player has an
inventory represented as a list of item names. You need to implement a function
that allows players to combine their inventories, ensuring that no duplicate items
are included in the combined inventory.Write a Python function
`combine_inventories(inventory1, inventory2)` that takes two lists representing
player inventories as input and returns a new list containing all unique items from
both inventories.
Example:
inventory1 = ["Sword", "Shield", "Potion"]
inventory2 = ["Shield", "Bow", "Arrow"]
combined_inventory = combine_inventories(inventory1, inventory2)
print(combined_inventory) # Output: ['Sword', 'Shield', 'Potion', 'Bow', 'Arrow']
Solution:
Args:
inventory1: A list of items in the first player's inventory.
inventory2: A list of items in the second player's inventory.
Returns:
A new list containing all unique items from both inventories.
"""
combined_inventory = inventory1 + inventory2
return list(set(combined_inventory))
# Example usage:
inventory1 = ["Sword", "Shield", "Potion"]
inventory2 = ["Shield", "Bow", "Arrow"]
Explanation:
1. Function Definition:
- `combine_inventories(inventory1, inventory2)`: Defines a function that takes
two lists as input.
2. Combine Inventories:
- `combined_inventory = inventory1 + inventory2`: Creates a new list by
combining the two input lists.
3. Remove Duplicates:
- `list(set(combined_inventory))`: Converts the combined list into a set. A set
by definition cannot contain duplicate elements. Then, it converts the set back
into a list.
This solution effectively combines the two inventories while ensuring that no
duplicate items are included in the final result.
Scenario:
You're developing a system to track student grades. Each student's grades for a
particular subject are stored as a tuple, where the first element represents the
student's ID and the remaining elements are their grades for various assessments
(e.g., quizzes, assignments, exams). Write a Python function
`calculate_average_grade(student_grades)` that takes a tuple of student grades as
input and calculates the average grade for that student.
Example:
student_grades = (12345, 85, 90, 78, 92) # Student ID: 12345, Grades: 85, 90, 78,
92
average_grade = calculate_average_grade(student_grades)
print(f"Average Grade for Student {student_grades[0]}: {average_grade}")
# Output: Average Grade for Student 12345: 86.25
Solution:
def calculate_average_grade(student_grades):
"""
Calculates the average grade for a student.
Args:
student_grades: A tuple where the first element is the student ID
and the remaining elements are the student's grades.
Returns:
The average grade of the student.
"""
grades = student_grades[1:] # Extract grades from the tuple
return sum(grades) / len(grades)
# Example usage:
student_grades = (12345, 85, 90, 78, 92)
average_grade = calculate_average_grade(student_grades)
print(f"Average Grade for Student {student_grades[0]}: {average_grade}")
Explanation:
1. Function Definition:
- `calculate_average_grade(student_grades)`: Defines a function that takes a
tuple as input.
2. Extract Grades:
- `grades = student_grades[1:]`: Creates a new list containing only the grades
by slicing the input tuple from the second element onwards.
3. Calculate Average:
- `sum(grades) / len(grades)`: Calculates the sum of all grades and divides it
by the number of grades to get the average.
This solution effectively calculates the average grade for a student given their
grades stored in a tuple. The use of a tuple is appropriate here as student grades
are typically immutable (not meant to be changed once recorded).
Scenario:
You're developing a system to track student grades. Each student's grades for a
particular subject are stored as a tuple of integers. You need to implement a
function that calculates the average grade for a given student.Write a Python
function `calculate_average_grade(grades)` that takes a tuple of integers
representing a student's grades as input and returns the average grade.
Example:
student_grades = (85, 92, 78, 90, 88)
average_grade = calculate_average_grade(student_grades)
print(average_grade) # Output: 86.6
Solution:
def calculate_average_grade(grades):
"""
Calculates the average grade of a student given a tuple of their grades.
Args:
grades: A tuple of integers representing the student's grades.
Returns:
The average grade of the student.
"""
if not grades:
return 0 # Handle empty tuple case
total_grades = sum(grades)
num_grades = len(grades)
average = total_grades / num_grades
return average
# Example usage:
student_grades = (85, 92, 78, 90, 88)
average_grade = calculate_average_grade(student_grades)
print(average_grade) # Output: 86.6
Explanation:
1. Function Definition:
- `calculate_average_grade(grades)`: Defines a function that takes a tuple of
integers (`grades`) as input.
This function effectively calculates the average grade of a student given their
grades stored as a tuple. Using tuples for storing grades is appropriate in this
scenario as:
- Immutability: Grades are typically considered immutable once recorded, and tuples
enforce this by preventing any modifications to the grade data.
- Readability: Tuples provide a clear and concise way to represent a collection of
related values (grades).
Scenario:
You are developing a social media application where users can follow other users.
Each user has a set of users they follow. You need to implement a function that
determines if two users are connected, meaning they follow each other.Write a
Python function `are_connected(user1_follows, user2_follows)` that takes two sets
as input, representing the users that `user1` and `user2` follow, respectively. The
function should return `True` if `user1` follows `user2` and `user2` follows
`user1`, and `False` otherwise.
Example:
user1_follows = {"userA", "userB", "userC"}
user2_follows = {"userB", "userC", "user1"}
Args:
user1_follows: A set of users that user1 follows.
user2_follows: A set of users that user2 follows.
Returns:
True if both users follow each other, False otherwise.
"""
return "user2" in user1_follows and "user1" in user2_follows
# Example usage:
user1_follows = {"userA", "userB", "userC"}
user2_follows = {"userB", "userC", "user1"}
Explanation:
1. Function Definition:
- `are_connected(user1_follows, user2_follows)`: Defines a function that takes
two sets as input.
3. Return Result:
- The function returns `True` if both conditions are met, and `False` otherwise.
This solution effectively determines if two users are connected in a social media
network by leveraging the efficient membership checks and uniqueness properties of
Python sets.
Scenario:
You are developing a social media application where users can follow other users.
You need to keep track of which users follow a particular user. Since the order of
followers is not important, you decide to use sets to represent the followers of
each user.Write a Python function `get_common_followers(user1_followers,
user2_followers)` that takes two sets representing the followers of two users as
input and returns a new set containing the followers that both users have in
common.
Example:
Solution:
Args:
user1_followers: A set of followers for the first user.
user2_followers: A set of followers for the second user.
Returns:
A set containing the followers that both users have in common.
"""
return user1_followers.intersection(user2_followers)
# Example usage:
user1_followers = {"Alice", "Bob", "Charlie"}
user2_followers = {"Bob", "David", "Alice"}
Explanation:
1. Function Definition:
- `get_common_followers(user1_followers, user2_followers)`: Defines a function
that takes two sets as input.
This example demonstrates how sets can be used effectively to represent and
manipulate relationships between entities, such as user-follower relationships in a
social media application.
Scenario:
You are building an online store that tracks the inventory of products. Each
product is represented by a dictionary with keys like "product_id", "product_name",
and "quantity". You need to implement a function to update the quantity of a
product in the inventory.Write a Python function `update_inventory(inventory,
product_id, new_quantity)` that takes the following as input:
inventory`: A list of dictionaries, where each dictionary represents a product in
the inventory.product_id`: The ID of the product to update.new_quantity`: The new
quantity of the product.
The function should update the quantity of the product with the given `product_id`
in the `inventory` list. If the product with the given `product_id` is not found,
the function should return `False`.
Example:
inventory = [
{"product_id": 1, "product_name": "Laptop", "quantity": 10},
{"product_id": 2, "product_name": "Phone", "quantity": 5},
{"product_id": 3, "product_name": "Headphones", "quantity": 20}
]
# Update the quantity of Laptop to 15
updated = update_inventory(inventory, 1, 15)
print(updated) # Output: True
print(inventory)
Output:
[
{"product_id": 1, "product_name": "Laptop", "quantity": 15},
{"product_id": 2, "product_name": "Phone", "quantity": 5},
{"product_id": 3, "product_name": "Headphones", "quantity": 20}
]
Solution:
Args:
inventory: A list of dictionaries, where each dictionary represents a product.
product_id: The ID of the product to update.
new_quantity: The new quantity of the product.
Returns:
True if the product was found and updated, False otherwise.
"""
for product in inventory:
if product["product_id"] == product_id:
product["quantity"] = new_quantity
return True
return False
# Example usage:
inventory = [
{"product_id": 1, "product_name": "Laptop", "quantity": 10},
{"product_id": 2, "product_name": "Phone", "quantity": 5},
{"product_id": 3, "product_name": "Headphones", "quantity": 20}
]
print(inventory)
Explanation:
1. Function Definition:
- `update_inventory(inventory, product_id, new_quantity)`: Defines a function
that takes the inventory list, the product ID, and the new quantity as input.
3. Find Product:
- `if product["product_id"] == product_id:`: Checks if the `product_id` of the
current product matches the given `product_id`.
4. Update Quantity:
- `product["quantity"] = new_quantity`: If the product is found, updates the
`quantity` of the product dictionary with the `new_quantity`.
Scenario:
You are building an online store that tracks the inventory of products. Each
product is represented by a dictionary with keys like "product_id", "product_name",
and "quantity". You need to efficiently manage the inventory by adding new
products, updating product quantities, and checking the availability of
products.Write Python code to:
1. Add a new product to the inventory.
2. Update the quantity of an existing product.
3. Check if a product is available in the inventory (i.e., if its quantity is
greater than zero).
Example Inventory:
inventory = {
"P001": {"product_name": "Laptop", "quantity": 10},
"P002": {"product_name": "Mouse", "quantity": 20},
"P003": {"product_name": "Keyboard", "quantity": 5}
}
Solution:
def add_product(inventory, product_id, product_name, quantity):
"""
Adds a new product to the inventory.
Args:
inventory: The current inventory dictionary.
product_id: The unique ID of the product.
product_name: The name of the product.
quantity: The initial quantity of the product.
Returns:
The updated inventory dictionary.
"""
inventory[product_id] = {"product_name": product_name, "quantity": quantity}
return inventory
Args:
inventory: The current inventory dictionary.
product_id: The ID of the product to update.
new_quantity: The new quantity of the product.
Returns:
The updated inventory dictionary.
"""
if product_id in inventory:
inventory[product_id]["quantity"] = new_quantity
return inventory
Args:
inventory: The current inventory dictionary.
product_id: The ID of the product to check.
Returns:
True if the product is available, False otherwise.
"""
return product_id in inventory and inventory[product_id]["quantity"] > 0
# Example Usage:
inventory = {
"P001": {"product_name": "Laptop", "quantity": 10},
"P002": {"product_name": "Mouse", "quantity": 20},
"P003": {"product_name": "Keyboard", "quantity": 5}
}
# Add a new product
inventory = add_product(inventory, "P004", "Monitor", 8)
Explanation:
- Dictionaries are ideal for representing key-value pairs: In this case, the
product ID serves as the key, and the product details (name and quantity) are
stored as values within a nested dictionary.
- add_product()`:
- Creates a new key-value pair in the dictionary with the `product_id` as the
key and a dictionary containing the `product_name` and `quantity` as the value.
- update_quantity()`:
- Checks if the `product_id` exists in the inventory.
- If it exists, updates the "quantity" value of the corresponding product.
- is_product_available():
- Checks if the `product_id` exists in the inventory.
- Checks if the "quantity" of the product is greater than zero.
- Returns `True` if both conditions are met, otherwise `False`.