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

pythonoutput

The document contains various Python programming examples demonstrating list comprehensions, tuple unpacking, set operations, dictionary merges, and more. Each example includes code snippets, expected outputs, and explanations of the results. The document also discusses the immutability of data structures and methods for reversing lists.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

pythonoutput

The document contains various Python programming examples demonstrating list comprehensions, tuple unpacking, set operations, dictionary merges, and more. Each example includes code snippets, expected outputs, and explanations of the results. The document also discusses the immutability of data structures and methods for reversing lists.

Uploaded by

Amol Adhangale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

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.

You might also like