0% found this document useful (0 votes)
0 views

python ques

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

python ques

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 73

What is the output of this nested list comprehension for a task scheduler?

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:

['Task A', 'Task C']


[['Task A', 1, 'In Progress'], ['Task B', 2, 'In Progress'], ['Task C', 1,
'Pending']]

Explanation: The list comprehension [task[0] for task in tasks if task[1] == 1]


creates a new list of task names (task[0]) where priority (task[1]) is 1, resulting
in ["Task A", "Task C"]. Modifying tasks[0][2] = "In Progress" updates the first
task’s status in the original list, but high_priority remains unchanged because
it’s a new list. The final tasks reflects the update.

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: (101, ('JFK', 'SFO'), ('2025-04-27', '10:00'))

Explanation: flight[1:] is (("JFK", "LAX"), ("2025-04-27", "08:00")). Unpacking


assigns dep = "JFK", arr = "LAX", date = "2025-04-27", and _ ignores "08:00". The
new tuple is created by concatenating flight[:1] (i.e., (101,)) with (("JFK",
"SFO"),) and (("2025-04-27", "10:00"),), resulting in (101, ("JFK", "SFO"), ("2025-
04-27", "10:00")).

What is the output of this set operation for a recommendation system?


user1_likes = {"Movie A", "Movie B", "Movie C"}
user2_likes = {"Movie B", "Movie D"}
common = user1_likes.intersection(user2_likes)
user1_likes.discard("Movie C")
print(common)
print(user1_likes)

Answer:

{'Movie B'}
{'Movie A', 'Movie B'}

Explanation: intersection() creates a new set common with elements in both


user1_likes and user2_likes, i.e., {"Movie B"}. discard("Movie C") removes "Movie
C" from user1_likes, leaving {"Movie A", "Movie B"}. The common set is unaffected
because it’s a separate set.

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:

['A1', 'A2', 'A3']


0

Explanation: bookings["Flight101"]["seats"] accesses the list ["A1", "A2"], and


append("A3") modifies it to ["A1", "A2", "A3"]. Adding Flight103 creates a new
entry with an empty seat list. len(bookings["Flight103"]["seats"]) returns 0
because the list is empty.

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])

Answer: ['Bob', 'Alice', 'Charlie']

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, 2), (5, 6)}

Explanation: points is a set of tuples, automatically removing duplicates, so it’s


{(1, 2), (3, 4)}. symmetric_difference() returns elements in either points or
other_points but not both. Since (3, 4) is in both, it’s excluded, leaving {(1, 2),
(5, 6)}.

What is the output of this set comprehension for a filtering system?


products = [
{"id": 1, "category": "Electronics"},
{"id": 2, "category": "Books"},
{"id": 3, "category": "Electronics"}
]
electronics_ids = {p["id"] for p in products if p["category"] == "Electronics"}
print(electronics_ids)

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.

What is the output of this dictionary merge for a configuration system?


config1 = {"host": "localhost", "port": 8080, "debug": True}
config2 = {"port": 9090, "user": "admin"}
merged = {**config1, **config2}
merged["debug"] = False
print(merged)
print(config1)

Answer:

{'host': 'localhost', 'port': 9090, 'debug': False, 'user': 'admin'}


{'host': 'localhost', 'port': 8080, 'debug': True}

Explanation: The ** operator unpacks dictionaries, merging config2 into config1. If


keys overlap (e.g., port), config2’s value (9090) takes precedence. Setting
merged["debug"] = False updates the new dictionary. config1 remains unchanged.

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)

Answer: [['A1', 'A2', 'B1'], [None, 'B3']]

Explanation: seating[0][2] = seating[1][0] assigns "B1" to the None at seating[0]


[2], making the first row ["A1", "A2", "B1"]. seating[1].pop(0) removes "B1" from
the second row, leaving [None, "B3"]. The final list is [["A1", "A2", "B1"], [None,
"B3"]].

What is the output of this dictionary of sets for a collaboration system?


teams = {
"Dev": {"Alice", "Bob"},
"QA": {"Bob", "Charlie"}
}
collabs = {team: members & teams["QA"] for team, members in teams.items()}
print(collabs)

Answer: {'Dev': {'Bob'}, 'QA': {'Bob', 'Charlie'}}

Explanation: The dictionary comprehension creates a dictionary mapping each team to


the intersection of its members with teams["QA"] (i.e., {"Bob", "Charlie"}). For
"Dev", {"Alice", "Bob"} & {"Bob", "Charlie"} yields {"Bob"}. For "QA", {"Bob",
"Charlie"} & {"Bob", "Charlie"} yields {"Bob", "Charlie"}.

Why can’t a list be used as a dictionary key, and what alternative would you use?

Answer: A list cannot be used as a dictionary key because it is mutable and


unhashable. Dictionary keys must be hashable, meaning they have a consistent hash
value (via __hash__). Since lists can change (e.g., lst.append(x)), their hash
value would become invalid, breaking the hash table’s integrity.

Alternative: Use a tuple, which is immutable and hashable, as a key if the list’s
contents are fixed.

Code:

# Invalid: d = {[1, 2]: "value"} # TypeError


# Valid alternative:
d = {(1, 2): "value"}
# d[(1, 2)] returns "value"

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?

Answer: There are three common ways to reverse a list:

Using reverse(): Modifies the list in-place.

Using slicing ([::-1]): Creates a new reversed list.

Using reversed(): Returns an iterator, which can be converted to a list.

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.

Use Case: Use reverse() for in-place modification in a memory-constrained app, or


[::-1] for a quick, readable new list in a data processing script.

What is the difference between sort( ) and sorted( )?

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.

Differences between Methods and Constructors.

Write a short program to print the following series :

1 -4 7 -10 .......... -40


Answer

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?

Rewrite following code fragments using while loops

for i in range(1, 16) :


if i % 3 == 0 :
print i
Answer

i = 1
while i < 16:
if i % 3 == 0 :
print (i)
i += 1

Rewrite following code fragments using while loops

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

Rewrite the following code fragments using for loop

while num > 0 :


print num % 10
num = num/10
Answer

l = [1]
for x in l:
l.append(x + 1)
if num <= 0:
break
print (num % 10)
num = num/10

Rewrite the following code fragments using for loop

i = 100
while (i > 0) :
print i
i -= 3
Answer

for i in range(100, 0, -3) :


print (i)

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.

numbers = list(range(0, 51, 4))


i = 0
while i < len(numbers):
print(numbers[i] , end = " ")
i += 3
# gives output as : 0 12 24 36 48
Answer

numbers = list(range(0, 51, 4))


i = len(numbers) - 1
while i >= 0:
print(numbers[i] , end = " ")
i -= 3
Output
48 36 24 12 0

What is the output of the following code?

numbers = list(range(0, 51, 4))


results = []
for number in numbers:
if not number % 3:
results.append(number)
print(results)
Answer

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.

What will be the output of following code?

x = ['3', '2', '5']


y = ''
while x:
y = y + x[-1]
x = x[:len(x) - 1]
print(y)
print(x)
print(type(x), type(y))
Answer

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.

Find the errors:

L1 = [3, 3, 8, 1, 3, 0, '1', '0', '2', 'e', 'w', 'e', 'r']


print(L1[: :-1])
print(L1[-1:-2:-3])
print(L1[-1:-2:-3:-4])
Answer

The line print(L1[-1:-2:-3:-4]) causes an error as its syntax is invalid. The


correct syntax for slicing a list is L1[start:stop:step].

Find the errors:

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.

Find the errors:

L1 = [1, 11, 21, 31]


An = L1.remove(31)
print(An + 2)
Answer

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.

Predict the output:

a, b, c = [1,2], [1, 2], [1, 2]


print(a == b)
print (a is b)
Answer
Output
True
False
Explanation
As corresponding elements of list a and b are equal hence a == b returns True. a is
b returns False as a and b are two different list objects referencing two different
memory locations.

Predict the output:

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.

Predict the output:

List1 = [13, 18, 11, 16, 13, 18, 13]


print(List1.index(18))
print(List1.count(18))
List1.append(List1.count(13))
print(List1)
Answer

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].

What will the following code result in?

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].

Given two lists:

L1 = ["this", 'is', 'a', 'List'], L2 = ["this", ["is", "another"], "List"]


Which of the following expressions will cause an error and why?

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

L1 == L2 gives output as false because L1 is not equal to L2.


L1[3].upper( ) gives output as 'LIST' because L1[3] is 'List' and upper() function
converts it to uppercase.
L2[1][1].upper( ) gives output as 'ANOTHER' because L2[1] ["is", "another"] and
L2[1][1] is "another". upper() function converts it to uppercase.

Given a list L1 = [3, 4.5, 12, 25.7, [2, 1, 0, 5], 88], which function can change
the list to:

[3, 4.5, 12, 25.7, 88]


[3, 4.5, 12, 25.7]
[ [2, 1, 0, 5], 88]
Answer

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]

(i) lst * 3 and lst *= 3


(ii) lst + 3 and lst += [3]

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
=====================================

Enter two equal sized lists


Enter first list: [80, 60, 50, 40, 30]
Enter second list: [80, 60, 50, 40, 30]
Lists are equal

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: "))

slice = l[start : stop + 1]


mx = max(slice)
mi = min(slice)

print("Maximum =", mx)


print("Minimum =", mi)
Output
Enter the list: [89, 42, 12, 56, 35, 2, 8, 7, 13, 69]
Enter start index: 3
Enter stop index: 8
Maximum = 56
Minimum = 2

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

print("Smallest Fraction =", num[smallIdx], "/", denum[smallIdx])


print("Index of Smallest Fraction =", smallIdx)
Output
Enter numerators list: [1, 3, 1, 7, 3]
Enter denominators list: [2, 4, 4, 13, 8]
Smallest Fraction = 1 / 2
Index of Smallest Fraction = 0

Write programs as per following specifications:

'''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]

Write programs as per following specifications:


'''Print the length of the longest
string in the list of strings str_list.
Precondition : the list will contain
at least one element.'''

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

print("Longest String:", l[largeIdx])


Output
Enter list of strings: ["apple", "orange", "pear", "strawberry", "kiwi"]
Longest String: strawberry

Write a program that reads the n to display nth term of Fibonacci series.

The Fibonacci sequence works as follows:

element 0 has the value 0


element 1 has the value 1
every element after that has the value of the sum of the two preceding elements
The beginning of the sequence looks like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

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

print(n, "term of Fibonacci series =", c)


Output
Enter n: 7
7 term of Fibonacci series = 13

=====================================

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]

Create the following lists using a for loop:

The list ['a','bb','ccc','dddd', . . . ] that ends with 26 copies of the letter z.


Solution
l = []

for i in range(1, 27):


l.append(chr(i + 96) * i)

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:])

print("List after removing first characters:")


print(l2)
Output
Enter a list of strings: ["red", "green", "blue", "pink", "cyan"]
List after removing first characters:
['ed', 'reen', 'lue', 'ink', 'yan']

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

print("List after removing numbers greater than 10:")


print(l)
Output
Enter list having numbers between 1 & 12: [1, 3, 15, 8, 20]
List after removing numbers greater than 10:
[1, 3, 10, 8, 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]

Write a program that reverses a list of integers (in place).

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]

Write a program to increment the elements of a list with a number.

Solution
lst = eval(input("Enter a list: "))
print("Existing list is:", lst)

n = int(input("Enter a number: "))

for i in range(len(lst)):
lst[i] += n

print("List after increment:", lst)


Output
Enter a list: [1, 2, 3, 4, 5]
Existing list is: [1, 2, 3, 4, 5]
Enter a number: 10
List after increment: [11, 12, 13, 14, 15]

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()

print("Nested tuple of student data is:", tup)

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

Enter the marks of student 2


Enter marks in first subject: 90
Enter marks in second subject: 89
Enter marks in third subject: 95

Enter the marks of student 3


Enter marks in first subject: 68
Enter marks in second subject: 70
Enter marks in third subject: 56

Enter the marks of student 4


Enter marks in first subject: 23
Enter marks in second subject: 56
Enter marks in third subject: 45

Enter the marks of student 5


Enter marks in first subject: 100
Enter marks in second subject: 98
Enter marks in third subject: 99

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

The total marks of student 2 = 274


The average marks of student 2 = 91.33333333333333

The total marks of student 3 = 194


The average marks of student 3 = 64.66666666666667

The total marks of student 4 = 124


The average marks of student 4 = 41.333333333333336

The total marks of student 5 = 297


The average marks of student 5 = 99.0

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()

print("Nested tuple of student data is:", tup)


Output
Enter the marks of student 1
Enter marks in first subject: 89
Enter marks in second subject: 78
Enter marks in third subject: 67

Enter the marks of student 2


Enter marks in first subject: 56
Enter marks in second subject: 89
Enter marks in third subject: 55

Enter the marks of student 3


Enter marks in first subject: 88
Enter marks in second subject: 78
Enter marks in third subject: 90

Enter the marks of student 4


Enter marks in first subject: 78
Enter marks in second subject: 67
Enter marks in third subject: 56

Enter the marks of student 5


Enter marks in first subject: 45
Enter marks in second subject: 34
Enter marks in third subject: 23

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)

while(fib[len(fib) - 1] < term):


fib_len = len(fib)
fib = fib + (fib[fib_len - 2] + fib[fib_len - 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)

print("9 terms of Fibonacci series are:", tup)


Output
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)

Consider the following code and then answer the questions that follow :

myDict = {'a' : 27, 'b' : 43, 'c' : 25, 'd' : 30}


valA =''
for i in myDict :
if i > valA :
valA = i
valB = myDict[i]
print(valA) #Line1
print(valB) #Line2
print(30 in myDict) #Line3
myLst = list(myDict.items())
myLst.sort() #Line4
print(myLst[-1]) #Line5
What output does Line 1 produce ?
What output does Line 2 produce ?
What output does Line 3 produce ?
What output does Line 5 produce ?
What is the return value from the list sort( ) function (Line 4) ?
Answer

The output of line 1 is : 'd'


The output of line 2 is: 30
The output of line 3 is: False
Since 30 is present in myDict as a value and not as a key.
The output of line 5 is: ('d',30)
myLst is a list which is created by dictionary items i.e myDict.items()
Hence, myLst will store ⇒ [('a', 27), ('b', 43), ('c', 25), ('d', 30)]
myLst.sort() will sort the list in ascending order according to the first element
of each tuple. Since the first elements of the tuples are all strings, Python
performs lexicographical sorting, which means that 'a' comes before 'b' and so on.
myLst[-1] will return last element of list i.e.,('d', 30).
The sort function in Line 4 will not return any value.
It will sort myLst in place in ascending order according to the first element of
each tuple. Since the first elements of the tuples are all strings, Python performs
lexicographical sorting, which means that 'a' comes before 'b' and so on. The
sorted myLst will be [('a', 27), ('b', 43), ('c', 25), ('d', 30)]

What will be the output produced by following code ?


d1 = { 5 : "number", "a" : "string", (1, 2): "tuple" }
print("Dictionary contents")
for x in d1.keys(): # Iterate on a key list
print (x, ':' , d1[x], end = ' ')
print (d1[x] * 3)
print ( )
Answer

Output
Dictionary contents
5 : number numbernumbernumber

a : string stringstringstring

(1, 2) : tuple tupletupletuple


Explanation
d1 is a dictionary containing three key-value pairs.
x in d1.keys() represents that x will iterate on the keys of d1.
The iterations are summarized below:

x d1[x] d1[x] * 3
5 number numbernumbernumber
a string stringstringstring
(1,2) tuple tupletupletuple

Predict the output:

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.

Predict 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:

Initialize the variables


The text variable stores the input string "abracadabraaabbccrr".
The counts variable is a dictionary that stores the frequency of each character in
the string.
The ct variable is a counter that keeps track of the total number of characters in
the string.
The lst variable is a list that stores the unique characters in the string.
Loop through each character word in the text string
If the character has not been seen before, it is added to the lst list and a new
key is added to the counts dictionary with a value of 0.
The ct variable is incremented by 1.
The value of the character's key in the counts dictionary is incremented by 1. This
value keeps a count of the number of times this character has appeared in the
string so far.
Finally, the counts dictionary and the lst list are printed to the console. The
counts dictionary displays the frequency of each character in the string, and the
lst list displays the unique characters in the string.

Predict the output:

list1 = [2, 3, 3, 2, 5,3, 2, 5, 1,1]


counts = {}
ct = 0
lst = []
for num in list1:
if num not in lst:
lst.append(num)
counts[num] = 0
ct = ct+1
counts[num] = counts[num]+1
print(counts)
for key in counts.keys():
counts[key] = key * counts[key]
print(counts)
Answer

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:

Initialize the variables


The list1 variable stores the input list [2, 3, 3, 2, 5, 3, 2, 5, 1, 1].
The counts variable is a dictionary that stores the frequency of each number in the
list.
The ct variable is a counter that keeps track of the total number of numbers in the
list.
The lst variable is a list that stores the unique numbers in the list.
Loop through each number num in the list1
If the number has not been seen before, it is added to the lst list and a new key
is added to the counts dictionary with a value of 0.
The ct variable is incremented by 1.
The value of the number's key in the counts dictionary is incremented by 1.
The counts dictionary is printed to the console after the first loop, displaying
the frequency of each number in the list.
Another loop is executed through the keys in the counts dictionary. For each key,
its corresponding value is multiplied by the key and the new value is assigned back
to the key in the counts dictionary.
The final counts dictionary is printed to the console, showing the frequency of
each number multiplied by the number itself.

Find the errors:

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.

Predict the output:

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:

Initialize the variables


The fruit variable is a dictionary that stores the frequency of each fruit.
The L1 variable stores the input list ['Apple', 'banana', 'apple'].
Loop through each fruit index in the list L1
If the fruit already exists as a key in the fruit dictionary, its value is
incremented by 1.
If the fruit is not in the fruit dictionary, a new key is added with a value of 1.
The length of the fruit dictionary is printed to the console, indicating the number
of unique fruits.
The fruit dictionary is printed to the console, showing the frequency of each
fruit.

Predict the output:

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.

The final value of the sum variable is printed to the console.

Predict the output

a = {'a':1, 'b':2, 'c':3}


print(a['a','b'])
Answer

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.

Predict the output :

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.

Here is a step-by-step explanation of the program:

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.

Nesting of dictionary allows you to store a dictionary inside another dictionary.


Then why is following code raising error ? What can you do to correct it ?

d1 = {1 : 10, 2 : 20, 3 : 30}


d2 = {1 : 40, 2 : 50, 3 : 60}
d3 = {1 : 70, 2 : 80, 3 : 90}
d4 = {d1 : "a", d2 : "b", d3 : "c"}
Answer

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:

d4 = { "a": d1, "b": d2, "c": d3}

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 = { (1, 2) : [1, 2], (3, 4) : [3, 4]}


dict2 = { ([1], [2]) : [1,2], ([3], [4]) : [3, 4]}
Answer

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]}

A dictionary D1 has values in the form of lists of numbers. Write a program to


create a new dictionary D2 having same keys as D1 but values as the sum of the list
elements e.g.,
D1 = {'A' : [1, 2, 3] , 'B' : [4, 5, 6]}
then
D2 is {'A' :6, 'B' : 15}

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}

Write a program to check if a dictionary is contained in another dictionary e.g.,


if

d1 = {1:11, 2:12}
d2 = {1:11, 2:12, 3:13, 4:15}

then d1 is contained in d2.

Solution
d1 = eval(input("Enter a dictionary d1: "))
d2 = eval(input("Enter a dictionary d2: "))

print("d1 =", d1)


print("d2 =", d2)

if len(d1) > len(d2):


longDict = d1
shortDict = d2
else:
longDict = d2
shortDict = d1

for key in shortDict:


if key in longDict:
if longDict[key] != shortDict[key]:
print("d1 and d2 are different ")
break
else:
print("d1 and d2 are different ")
break
else:
print(shortDict, "is contained in", longDict)
Output
Enter a dictionary d1: {1:11, 2:12}
Enter a dictionary d2: {1:11, 2:12, 3:13, 4:15}
d1 = {1: 11, 2: 12}
d2 = {1: 11, 2: 12, 3: 13, 4: 15}
{1: 11, 2: 12} is contained in {1: 11, 2: 12, 3: 13, 4: 15}

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: "))

print("First dictionary: ", d1)


print("Second dictionary: ", d2)

if len(d1) > len(d2):


longDict = d1
shortDict = d2
else:
longDict = d2
shortDict = d1

print("overlapping keys in the two dictionaries are:", end=' ')


for i in shortDict:
if i in longDict:
print(i, end=' ')
Output
Enter first dictionary: {'a': 1, 'b':2, 'c': 3, 'd': 4}
Enter second dictionary: {'c': 3, 'd': 4, 'e': 5}
First dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Second dictionary: {'c': 3, 'd': 4, 'e': 5}
overlapping keys in the two dictionaries are: c d

Given the dictionary x = {'k1':'v1', 'k2':'v2', 'k3':'v3'}, create a dictionary


with the opposite mapping, i.e., write a program to create the dictionary as :
inverted_x = {'v1': 'k1' , 'v2' :'k2' , 'v3':'k3'}

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.

(b) Print out all of the keys in alphabetical order.

(c) Print out all of the months with 31 days.

(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
}

m = input("Enter name of month: ")

if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)

print("Months in alphabetical order are:", sorted(days_in_months))

print("Months with 31 days:", end=" ")


for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")

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): ")

team = input("Enter team name for winning percentage: ")


if team not in d:
print("Team not found", team)
else:
wp = d[team][0] / sum(d[team]) * 100
print("Winning percentage of", team, "is", wp)

w_team = []
for i in d.values():
w_team.append(i[0])

print("Number of wins of each team", w_team)

w_rec = []
for i in d:
if d[i][0] > 0:
w_rec.append(i)

print("Teams having winning records are:", w_rec)

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)

Write a program in Python to input elements in an empty list. Also delete an


element from the list which a user will input.

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 create a class named as Product. Product has following


attribute
Attribute details Attribute Name
Unique identification number id
Product Name name
Product Price price
Product Quantity qty
Define following methods and constructor :
constructor to initialise Product id.
Method to get product details as Name,Price and Quantity
Method to display a product.

Predict the output of the Python code given below:


Text1 = "IND-23"
Text2 = ""
I = 0
while I < len(Text1):
if Text1[I] >= "0" and Text1[I] <= "9":
Val = int(Text1[I])
Val = Val + 1
Text2 = Text2 + str(Val)
elif Text1[I] >= "A" and Text1[I] <= "Z":
Text2 = Text2 + (Text1[I + 1])
else:
Text2 = Text2 + "*"
I += 1
print(Text2)
Answer
Output
ND-*34
Explanation
The provided Python code initializes a variable Text1 with the string value "IND-
23". Then it initializes an empty string variable Text2 and an index variable I
with the value 0. The while loop continues as long as I is less than the length of
Text1. Within the loop, each character of Text1 is checked: if it's a digit (0-9),
it increments the digit by 1 and appends it to Text2; if it's an uppercase letter
(A-Z), it appends the next character in Text1 to Text2; otherwise, it appends an
asterisk "*". After processing all characters, the final value of Text2 is printed.

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)

print("Count of character",ch,"in",str,"is :", c)

What is the difference between add() and update() functions in set

Write a program that uses a while loop to add up all the even numbers between 100
and 200.

Predict the output of the following code:


def Changer(P, Q = 10):
P = P / Q
Q = P % Q
return P
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 '###'.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------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

Predict the output of the following code:


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 "*".

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------Name the three ways of creating a dictionary in Python?

write a program using function definition to print multiplication of all the


numbers in a list.

Find and write the output of the following python code:


for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] :
print (Name)
if Name[0] == 'T' :
break
else :
print ('Finished!')
print ('Got it!')
Answer

Output
Jay
Finished!
Riya
Finished!
Tanu
Got it!

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------

What are the various types of arguments in python.

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?

for i in range(-1, 7, -2):


for j in range (3):
print(1, j)
Answer

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.

Predict the output of the following code fragments:

x ='apple, pear, peach, grapefruit'


y = x.split(', ')
for z in y:
if z < 'm':
print(str.lower(z))
else:
print(str.upper(z))
Answer

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.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------

what are th 4 different ways to create tuples in python.

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.

Predict the output of the following code fragments:


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.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------

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.

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.

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------

How to remove duplicate elements from a list.

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.'

Predict the output of the following code fragments:

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)

Predict the output of the following code fragments:

x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer

This code generates No Output.

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

Thus range(x-y * 2) is equivalent to range(0) which returns an empty sequence —


[ ].

Write a program to take a tuple of numbers from the keyboard and print its sum and
average

Predict the output of the following code fragments:

for z in range(-500, 500, 100):


print (z)
Answer

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'}

What will be the output of the following code snippet ?

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

What will be the output of the following code snippet ?

rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}


id1 = id(rec)
del rec
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id2 = id(rec)
print(id1 == id2)

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

Predict the output of the following code snippet ?

Numbers = [9, 18, 27, 36]


for Num in Numbers :
for N in range(1, Num % 8) :
print(N, "#", end=" ")
print( )
Answer

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.

Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as


an argument and displays the names (in uppercase)of the places whose names are
longer than 5 characters.For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}.The output should
be:LONDON NEW YORK

Predict the output of the following code snippet?

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 function, lenWords(STRING), that takes a string as an argument and returns


a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun", the tuple will have (4,
3, 2, 4, 4, 3)

Write a program in Python to input elements in an empty list. Also delete an


element from the list which a user will input.

Write a Python program to find the highest 2 values in a dictionary.

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 read a list of n integers (positive as well as negative). Create


two new lists, one having all positive numbers and the other having all negative
numbers from the given list. Print all three lists.

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 n integers and find their median.


Note: The median value of a list of values is the middle one when they are arranged
in order. If there are two middle values, then take their average.
Hint: Use an inbuilt function to sort the list.

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 to read elements of a list and do the following:


(a) The program should ask for the position of the element to be deleted from the
list and delete the element at the desired position in the list.
(b) The program should ask for the value of the element to be deleted from the list
and delete this value from the list.

Write a program that accepts elements of a list S and adds all the odd values and
displays the sum.

Write a program to calculate mean of a given list of numbers.

WAP in Python to delete all duplicate elements in a list.

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 to check if the smallest element of a tuple is present at the


middle position of the tuple.

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 to count the number of each vowel in a given string.

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.)

Given the dictionary x = {'k1':'v1', 'k2':'v2', 'k3':'v3'}, create a dictionary


with the opposite mapping, i.e., write a program to create the dictionary as :
inverted_x = {'v1': 'k1' , 'v2' :'k2' , 'v3':'k3'}

Predict the output of the Python code given below:


Text1 = "IND-23"
Text2 = ""
I = 0
while I < len(Text1):
if Text1[I] >= "0" and Text1[I] <= "9":
Val = int(Text1[I])
Val = Val + 1
Text2 = Text2 + str(Val)
elif Text1[I] >= "A" and Text1[I] <= "Z":
Text2 = Text2 + (Text1[I + 1])
else:
Text2 = Text2 + "*"
I += 1
print(Text2)
Answer
Output
ND-*34
Explanation
The provided Python code initializes a variable Text1 with the string value "IND-
23". Then it initializes an empty string variable Text2 and an index variable I
with the value 0. The while loop continues as long as I is less than the length of
Text1. Within the loop, each character of Text1 is checked: if it's a digit (0-9),
it increments the digit by 1 and appends it to Text2; if it's an uppercase letter
(A-Z), it appends the next character in Text1 to Text2; otherwise, it appends an
asterisk "*". After processing all characters, the final value of Text2 is printed.

Predict the output of the following code:

def Changer(P, Q = 10):


P = P / Q
Q = P % Q
return P

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 '###'.

Predict the output of the following code:

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 "*".

Find and write the output of the following python code:

for Name in ['Jay', 'Riya', 'Tanu', 'Anil'] :


print (Name)
if Name[0] == 'T' :
break
else :
print ('Finished!')
print ('Got it!')
Answer

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

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.

How many times will the following for loop execute and what's the output?

for i in range(-1, 7, -2):


for j in range (3):
print(1, j)
Answer

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.

Predict the output of the following code fragments:

x ='apple, pear, peach, grapefruit'


y = x.split(', ')
for z in y:
if z < 'm':
print(str.lower(z))
else:
print(str.upper(z))
Answer

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.

Predict the output of the following code fragments:

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.

Predict the output of the following code fragments:

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.

Predict the output of the following code fragments:

x = 10
y = 5
for i in range(x-y * 2):
print (" % ", i)
Answer

This code generates No Output.

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

Thus range(x-y * 2) is equivalent to range(0) which returns an empty sequence —


[ ].

Predict the output of the following code fragments:

for z in range(-500, 500, 100):


print (z)
Answer

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.

What will be the output of the following code snippet ?

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}

What will be the output of the following code snippet ?

rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}


id1 = id(rec)
del rec
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id2 = id(rec)
print(id1 == id2)

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.

Predict the output of the following code snippet ?

Numbers = [9, 18, 27, 36]


for Num in Numbers :
for N in range(1, Num % 8) :
print(N, "#", end=" ")
print( )
Answer

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.

Predict the output of the following code snippet?

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.

Creating a dictionary with dictionary comprehension

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.

# Python program to create a dictionary using dictionary comprehension.


# Creating a list of elements of string type.
names = ['Alice', 'Bob', 'Saanvi', 'Mahika']

# This statement creates a dictionary containing names as keys and their


corresponding lengths as values.
dict = {name: len(name) for name in names}
print(dict)
PYTHON

Output:
{'Alice': 5, 'Bob': 3, 'Saanvi': 6, 'Mahika': 6}

# Creating a list of elements of string type.


names = ['Alice', 'Bob', 'Saanvi', 'Mahika']

# Creating an empty dictionary.


dict = {}
for name in names:
dict[name] = len(name)
print(dict)

# Python program to swap keys and values in a dictionary using dictionary


comprehension.
# Creating a dictionary.
org_dict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

# This statement swapped keys and values.


swapped_dict = {value: key for key, value in org_dict.items()}

# Displaying the result.


print(swapped_dict)

# Python program to create a dictionary from two lists using dictionary


comprehension.
# Creating two lists.
keys = [1, 2, 3, 4]
values = ["one", "two", "three", "four"]

# 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)

# Python program to create a dictionary from a list of tuples using dictionary


comprehension.
# Creating a list of tuples.
tuple_list = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

# This statement creates a dictionary from a list of tuples.


dict_from_tuples = {key: value for key, value in tuple_list}
print(dict_from_tuples)

we have a dictionary of students and their scores. We want to create a new


dictionary that only includes the students who scored above a certain threshold.

Filtering dictionary items based on a condition

# Python program to filter data using dictionary comprehension.


# Creating a dictionary of five entries.
st_dict = {'Alice': 80, 'Bob': 75, 'Mahika': 90, 'Deep': 85, 'Mark': 72}

# This statement will filter data based on the specified condition.


top_students = {name: score for name, score in st_dict.items() if score > 80}

# Displaying the resulted dictionary.


print(top_students)

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.

# Python program to modify data using dictionary comprehension.


# Creating a dictionary of four entries.
fr_prices = {'apple': 2.90, 'banana': 1.99, 'orange': 0.99, 'Mango': 3.99}

# This statement will discount 20% of all prices.


dis_prices = {product: price * 0.8 for product, price in fr_prices.items()}

# Displaying the resulting discounted prices on the console.


print(dis_prices)

Let’s look at a program in which we will find all numbers between 1 to 30 divisible
by 2 and 5.

nums = {x for x in range(1, 31) if x % 2 == 0 if x % 5 == 0}


print(nums)
PYTHON
Output:
{10, 20, 30}

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.

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


flattened_list = [num for sublist in nested_list for num in sublist]
print(flattened_list)
PYTHON
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
l1 = [1, 2, 3]
l2 = [4, 5, 6]
l3 = [(x, y) for x in l1 for y in l2]
print(l3)

# Python program to check for duplicates in list

# take list
my_list = [1, 7, 8, 1, 5]

# printing original list


print('List:', my_list)

# check duplicates using count()


duplicate_item = {x for x in my_list if my_list.count(x) > 1}
if duplicate_item:
print('Yes, the list contains duplicates.')
else:
print('No, the list does not contains duplicates.')

**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_amount", and "order_date".

**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

# Sample order data (replace with your actual data)


orders = [
{'customer_id': 1, 'order_amount': 100, 'order_date': '2024-07-05'},
{'customer_id': 2, 'order_amount': 150, 'order_date': '2024-07-20'},
{'customer_id': 3, 'order_amount': 80, 'order_date': '2024-06-25'},
{'customer_id': 4, 'order_amount': 200, 'order_date': '2024-07-18'},
]

# Calculate the date 30 days ago


today = datetime.now()
thirty_days_ago = today - timedelta(days=30)

# Use list comprehension to filter orders and extract amounts


recent_order_amounts = [
order['order_amount']
for order in orders
if datetime.strptime(order['order_date'], '%Y-%m-%d') >= thirty_days_ago
]

print(recent_order_amounts)
```

**Explanation:**

1. **Import necessary modules:**


- `datetime`: Provides functions for working with dates and times.

2. **Sample data:**
- `orders`: A list of dictionaries, each representing an order.

3. **Calculate 30 days ago:**


- `today`: Get the current date and time.
- `thirty_days_ago`: Calculate the date 30 days ago.

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.

5. **Print the result:**


- Print the list of recent order amounts.

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:**

Imagine you're an analyst at an e-commerce company. You have a list of customer


orders, each represented as a tuple containing the customer ID, order ID, and order
amount.

* **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)
]

# List comprehension solution


high_value_orders = [order_id for customer_id, order_id, amount in orders if
customer_id > 1000]

print(high_value_orders) # Output: ['ORD456', 'ORD101']


```

**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:

High-Value Customers: Write a list comprehension to create a list of customer IDs


for all customers who have made orders with a total amount greater than $1000.

Orders in a Specific Month: Write a list comprehension to create a list of order


dates for all orders placed in January.

Popular Items: Write a list comprehension to create a list of unique item names
that appear in more than 5 orders.

Example Solution (for Question 1):

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']}
]

high_value_customers = [order['customer_id'] for order in orders if


order['total_amount'] > 1000]
print(high_value_customers) # Output: [1, 3]
Explanation:

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?

This scenario demonstrates how list comprehensions can be used to efficiently


process and analyze data, making them a valuable tool for data scientists and
analysts.

**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:**

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.

2. **Orders in a Specific Month:**


- Write a list comprehension to create a list of order dates for all orders
placed in the month of July.

3. **Popular Products:**
- Write a list comprehension to create a list of all unique product names that
appear in any order.

**Example Data (Simplified):**

```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:**

* **List Comprehension Structure:**


- `[expression for item in iterable if condition]`
- `expression`: The value to include in the new list.
- `item`: The current item being processed from the iterable.
- `iterable`: The data source (e.g., a list, dictionary).
- `condition` (optional): A filter to include only certain items.

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.

**Note:** This is a simplified example. In a real-world scenario, you might need to


handle more complex data structures and perform more sophisticated analysis.

**Scenario:**

Imagine you're an analyst at an e-commerce company. You have a list of customer


orders, each represented as a tuple containing the customer ID, order amount, and
order date.

**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')
]

# Assuming today is 2024-12-15


```

**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
]

print(recent_orders) # Output: [50, 75]


```

**Explanation:**

1. **Import necessary modules:**


- `datetime`: Provides functions for working with dates and times.

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:**

Using list comprehension, write Python code to:

1. **Extract a list of order dates** from all orders.


2. **Create a list of customer IDs** who made orders with a total amount greater
than $100.
3. **Generate a list of unique items** ordered by all customers.

**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']}
]

# 1. Extract a list of order dates


order_dates = [order['order_date'] for order in orders]
print("Order Dates:", order_dates)

# 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)

# 3. Generate a list of unique items ordered by all customers


unique_items = list(set([item for order in orders for item in order['items']]))
print("Unique Items:", unique_items)
```

**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:**

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_amount", and "order_date". Your task is to analyze this data and identify
customers who have made multiple orders within a specific time frame (e.g., within
the last 30 days).

**Challenge:**

Use list comprehension to create a list of customer IDs who meet the following
criteria:

1. Have made at least two orders.


2. The orders were placed within the last 30 days.

**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
}

print(list(repeat_customers)) # Output: [1, 2]


```

**Explanation:**

1. **Import necessary modules:**


- `datetime`: For working with dates and time.
2. **Calculate today's date and 30 days ago:**
- `today`: Stores the current date and time.
- `thirty_days_ago`: Calculates the date 30 days ago.

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.

4. **Create a set of repeat customers:**


- The use of a set (`{customer_id}`) ensures that each customer ID appears only
once in the result, even if they have multiple orders within the time frame.

5. **Print the result:**


- Convert the set of customer IDs back to a list and print it.

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:**

Create a Python function `can_craft(player_inventory, required_items)` that:

1. Takes two arguments:


- `player_inventory`: A list of strings representing the items currently in the
player's inventory.
- `required_items`: A list of strings representing the items required to craft
the desired item.

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"]

print(can_craft(player_inventory, required_items)) # Output: True

player_inventory = ["wood", "stone"]


required_items = ["wood", "stone", "iron"]

print(can_craft(player_inventory, required_items)) # Output: False


```

**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`.

2. **Iterate through Required Items:**


- The code iterates through each item in the `required_items` list.

3. **Check for Item Availability:**


- Inside the loop, it checks if the current `item` is present in the
`player_inventory` list using the `in` operator.

4. **Return False if Item is Missing:**


- If the `item` is not found in the `player_inventory`, the function immediately
returns `False`, indicating that the player cannot craft the item.

5. **Return True if All Items are Found:**


- If the loop completes without encountering any missing items, the function
returns `True`, indicating that the player has all the required items to craft the
item.

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.

Certainly, here's a scenario-based question on lists in Python:

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 add_item(inventory, item_name, item_weight):


"""Adds an item to the player's inventory."""
inventory.append({"name": item_name, "weight": item_weight})

def remove_item(inventory, item_name):


"""Removes an item from the player's inventory."""
for i in range(len(inventory)):
if inventory[i]["name"] == item_name:
inventory.pop(i)
break

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")

print("Total weight:", get_total_weight(inventory))


display_inventory(inventory)

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.

I hope this scenario-based question is helpful! Let me know if you'd like to


explore more complex list-related challenges or have any other questions.

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:**

```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"]

combined_inventory = combine_inventories(inventory1, inventory2)


print(combined_inventory) # Output: ['Sword', 'Shield', 'Potion', '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.

4. **Return the Result:**


- Returns the new list containing all unique items.

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:

def combine_inventories(inventory1, inventory2):


"""
Combines two player inventories, removing any duplicate items.

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"]

combined_inventory = combine_inventories(inventory1, inventory2)


print(combined_inventory) # Output: ['Sword', 'Shield', 'Potion', '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.

4. Return Unique Items:


- The function returns the list containing all unique items from both
inventories.

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.

4. Return Average Grade:


- The function returns the calculated average grade.

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.

2. Handle Empty Tuple:


- `if not grades:`: Checks if the `grades` tuple is empty. If it's empty, the
function returns 0 as there are no grades to average.

3. Calculate Total Grades:


- `total_grades = sum(grades)`: Calculates the sum of all grades in the tuple
using the `sum()` function.

4. Calculate Number of Grades:


- `num_grades = len(grades)`: Calculates the number of grades in the tuple using
the `len()` function.

5. Calculate Average Grade:


- `average = total_grades / num_grades`: Calculates the average grade by
dividing the `total_grades` by the `num_grades`.

6. Return Average Grade:


- `return average`: Returns the calculated average grade.

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).

This example demonstrates how tuples can be effectively used in real-world


scenarios to represent and process data with specific characteristics.

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"}

connected = are_connected(user1_follows, user2_follows)


print(connected) # Output: True
Solution:

def are_connected(user1_follows, user2_follows):


"""
Checks if two users are connected, meaning they follow each other.

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"}

connected = are_connected(user1_follows, user2_follows)


print(connected) # Output: True

Explanation:

1. Function Definition:
- `are_connected(user1_follows, user2_follows)`: Defines a function that takes
two sets as input.

2. Check for Mutual Following:


- `return "user2" in user1_follows and "user1" in user2_follows`:
- `in` operator efficiently checks if an element exists within a set.
- This single line checks if `user2` is present in the set of users `user1`
follows, and if `user1` is present in the set of users `user2` follows.
- The `and` operator ensures that both conditions must be True for the users
to be considered connected.

3. Return Result:
- The function returns `True` if both conditions are met, and `False` otherwise.

Why Sets are Suitable:

- Uniqueness:Sets inherently do not allow duplicate entries, which is ideal for


representing relationships where each user can only follow another user once.
- Efficient Membership Checks:Sets provide very fast membership checks using the
`in` operator, making the `are_connected` function efficient for large numbers of
users.

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:

user1_followers = {"Alice", "Bob", "Charlie"}


user2_followers = {"Bob", "David", "Alice"}

common_followers = get_common_followers(user1_followers, user2_followers)


print(common_followers) # Output: {'Alice', 'Bob'}

Solution:

def get_common_followers(user1_followers, user2_followers):


"""
Finds the common followers between two users.

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"}

common_followers = get_common_followers(user1_followers, user2_followers)


print(common_followers) # Output: {'Alice', 'Bob'}

Explanation:

1. Function Definition:
- `get_common_followers(user1_followers, user2_followers)`: Defines a function
that takes two sets as input.

2. Find Common Followers:


- `user1_followers.intersection(user2_followers)`: Uses the `intersection()`
method of the first set to find the common elements between the two sets. The
`intersection()` method returns a new set containing only the elements that are
present in both sets.

3. Return Common Followers:


- The function returns the set of common followers.

This solution effectively utilizes the properties of sets in Python to efficiently


find the common followers between two users. Sets are well-suited for this task
because:
- Uniqueness: Sets inherently do not allow duplicate elements, ensuring that each
follower is counted only once.
- Efficient Membership Tests: Sets provide fast membership tests (`in` operator),
making it efficient to check if a user is a follower of both users.
- Efficient Intersection: The `intersection()` method provides a built-in and
efficient way to find the common elements between two sets.

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:

def update_inventory(inventory, product_id, new_quantity):


"""
Updates the quantity of a product in the inventory.

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}
]

# Update the quantity of Laptop to 15


updated = update_inventory(inventory, 1, 15)
print(updated) # Output: True

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.

2. Iterate through Inventory:


- `for product in inventory:`: Iterates through each product dictionary in the
`inventory` list.

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`.

5. Return True (Product Found and Updated):


- `return True`: If the product is found and updated, the function returns
`True`.

6. Return False (Product Not Found):


- `return False`: If the product is not found in the inventory, the function
returns `False`.

This solution effectively utilizes dictionaries to represent and manage product


information, and the function efficiently updates the quantity of a specific
product within the inventory.

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

def update_quantity(inventory, product_id, new_quantity):


"""
Updates the quantity of an existing product.

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

def is_product_available(inventory, product_id):


"""
Checks if a product is available in the 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)

# Update the quantity of an existing product


inventory = update_quantity(inventory, "P001", 15)

# Check if a product is available


print(is_product_available(inventory, "P001")) # Output: True
print(is_product_available(inventory, "P005")) # Output: False

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`.

This solution effectively demonstrates how dictionaries can be used to efficiently


manage and track inventory in an online store.

You might also like