Question 1: Extract every third element from a list
The goal is to extract the elements at the 3rd, 6th, 9th, and so on, positions
(which correspond to indices 2, 5, 8, etc., in Python's 0-based indexing) from
the list my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90].
Method 1: List Slicing (my_list[2::3])
This is the most concise and idiomatic Python approach. List slicing is
used with a start, stop, and step argument in the format [start:stop:step].
Here, 2 is the start index (the third element), the stop index is omitted
(meaning it goes to the end of the list), and 3 is the step, which tells Python
to skip two elements and select the third one repeatedly.
Method 2: List Comprehension and range
This method uses a list comprehension to iterate through the list indices
generated by range(len(my_list)). Inside the comprehension, an if condition
filters the indices. The condition (i + 1) % 3 == 0 checks if the position of
the element (index i + 1, since positions are 1-based) is perfectly divisible by
3. If it is, the element at that index, my_list[i], is included in the new list.
Method 3: List Comprehension and enumerate
This method also uses a list comprehension but utilizes the enumerate
function, which provides both the index and the value of the list elements
during iteration. By setting start=1 in enumerate, the index y acts as the 1-
based position number. The if condition y % 3 == 0 directly checks if the
position number is a multiple of 3, and the value x (the element) is selected
and added to the new list.
Question 2: Remove the first and last element from a list using
slicing
Starting with the list my_list = [10, 20, 30, 40, 50, 60, 70, 80, 90], the goal is
to create a new list containing elements from the second up to the second-
to-last element.
Method 1: Forward Slicing (my_list[1:-1])
This is the simplest slicing approach. The slice starts at index 1 (the second
element) and ends before index -1. In Python, a negative index like -1 refers
to the last element. The slice notation [start:stop] is non-inclusive of the stop
index, so :-1 effectively means "up to, but not including, the last element."
Method 2: Explicit Step = 1 (my_list[1:-1:1])
This is identical in function to Method 1. By explicitly adding the step of 1 in
the slice [1:-1:1], it clearly indicates a forward traversal. While redundant, it
serves as a complete demonstration of the list slicing syntax.
Method 3: Twice (Chained Slicing) (my_list[1:][:-1])
This method uses two separate chained slice operations. The first slice,
my_list[1:], creates a temporary list that removes the first element (starts at
index 1 and goes to the end). The second slice, [:-1], is then applied to this
temporary list, removing its last element (which was the original list's
second-to-last element).
Method 4: Reverse Slicing then Reverse Again (my_list[::-1][1:-1][::-
1])
This is a more complex, multi-step slicing approach. The first slice, my_list[::-
1], reverses the list. The second slice, [1:-1], removes the first and last
elements from the reversed list (which were the original list's last and first
elements, respectively). Finally, the third slice, [::-1], reverses the list back to
its original order, resulting in the desired list with the original first and last
elements removed.
Question 3: Create a tuple with 5 elements and access the third
element
The task is to create a tuple my_tuple = (10, 20, 30, 40, 50) and retrieve the
element at the third position.
Method 1: Positive Indexing (my_tuple[2])
Python uses 0-based indexing, meaning the first element is at index 0, the
second at index 1, and the third at index 2. This method uses the simple
positive index 2 within square brackets to directly access the third element.
Method 2: Negative Indexing (my_tuple[-3])
Negative indexing counts from the end of the sequence. The last element
is at index -1, the second-to-last at -2, and the third element from the end is
at index -3. In this 5-element tuple, the third element from the start is also
the third element from the end, which is accessed using the index -3.
Method 3: enumerate and Loop
This method demonstrates accessing an element by its 1-based position
using a for loop and the enumerate function. enumerate(my_tuple, start=1)
provides a counter x (the position, starting at 1) and the element y. The loop
checks if the position x is equal to 3. If it is, the element y is printed.
Question 4: Convert a tuple to list and add a new element
The task is to convert the tuple my_tuple into a mutable list, add the element
60, and display the resulting list.
Method 1: Iterative Conversion and append
This method manually converts the tuple to a list using a for loop. It
initializes an empty list, new_list, and then iterates through each element i in
my_tuple, using the append() method to add it to new_list. Finally, the new
element 60 is added to the end of the list using append().
Method 2: list() Constructor and insert()
This is the most direct and efficient method for conversion. The built-in
list() constructor is called with the tuple as an argument, instantly
converting it to a list called tup_list. Then, the insert() method is used to add
the new element 60. The arguments len(my_list) (though len(tup_list) would
be more correct, as my_list is an older, different list) and 60 are passed,
which inserts the value 60 at the specified index, effectively adding it to the
end. The standard practice for appending is using tup_list.append(60), but
insert(len(tup_list), 60) also works.
Question 5: Create a dictionary of 5 students with their scores and
print all keys
The goal is to create a dictionary mapping student names to scores and then
print the names (keys) of all students.
Method 1: [Link]()
This method uses the built-in keys() method of the dictionary, which
returns a view object containing all the keys in the dictionary. Printing this
view object directly displays all the keys. To get a standard list of keys, one
would cast it using list([Link]()).
Method 2: Iterating through the Dictionary (for name in students:)
When a for loop iterates directly over a dictionary object, it defaults to
iterating over the keys of the dictionary. Each key (name) is retrieved in turn
and then printed individually.
Method 3: list(map(str, [Link]()))
This method first calls the keys() method (as in Method 1) to get the keys
view. It then uses the map() function to apply the built-in str function to
every item in the keys view (though str is redundant here since keys are
already strings). Finally, the result of map is converted into a standard list
using the list() constructor, which is then printed. A much simpler alternative
is list([Link]()).
Question 6: Update the score of a student in a dictionary
The task is to modify the score (value) associated with a student (key) in the
existing students dictionary.
Method 1: Direct Key Assignment (students["student_3"] = 80)
This is the most straightforward and common way to update a dictionary
value. By referencing the existing key ("student_3") using square bracket
notation and assigning a new value (80) to it, the value associated with that
key is overwritten.
Method 2: Looping and enumerate (Indexed Update)
This method updates the score of the 4th student ("student_4") by combining
iteration, indexing, and direct key assignment. The enumerate function is
used to get a 1-based index (index) and the key (key) for each dictionary
item. It checks if the index equals a target number (n=4), and if so, it uses
the key to update the value with new_score (100). This method is generally
overly complicated for a direct update, as dictionary order is not
guaranteed in all Python versions (though it is in modern versions).
Method 3: Dictionary Comprehension
This method uses a dictionary comprehension to create a new dictionary
based on the old one, but with an updated value for a specific key. It iterates
through the key-value pairs (k, v) of the original dictionary. For each pair, a
ternary operator checks if the key k is equal to "student_2". If it is, the new
value is set to 120; otherwise, the original value v is kept.
Method 4: pop() and Re-insertion with sorted()
This method involves removing the old key-value pair and then inserting the
new one, followed by sorting. First, [Link]("student_3", None)
removes the key-value pair for "student_3" (the None prevents an error if the
key doesn't exist). Second, the new key-value pair is inserted with
students["student_3"] = 300. Finally, the dictionary is recreated using
dict(sorted([Link]())) to ensure the keys are in alphabetical (and
thus numerical student number) order, although dictionary order is
maintained by insertion in recent Python versions.
Question 7: Print all even numbers from a list using a for loop
The goal is to iterate through the list numbers = [10, 15, 20, 25, 30, 35, 40]
and print only the numbers that are even.
Method 1: Standard for Loop and if Condition
This is the most direct and traditional approach. A for loop iterates over
each num in the numbers list. Inside the loop, an if statement checks for
evenness using the modulo operator: num % 2 == 0. If the remainder of the
number divided by 2 is 0, the number is even and is printed.
Method 2: List Comprehension with Index Filtering
This method attempts to filter the list using a list comprehension.
However, the condition if num % 2 == 0 filters on the index num being
even, not the list element numbers[num]. For the list [10, 15, 20, 25, 30, 35,
40], the indices are 0, 1, 2, 3, 4, 5, 6. The code filters for even indices (0, 2,
4, 6), selecting the elements [10,20,30,40]. This incidentally works for the
elements because the list starts with an even number at an even index, but
is an incorrect application of the logic if the intent was to filter based on the
value of the number itself, as shown in the more correct Method 1. The
correct list comprehension to filter for even values would be [num for num in
numbers if num % 2 == 0].
Question 8: Count how many times a specific word appears in a list
Given the list of colors and a target = "Violet", the goal is to count its
occurrences.
Method 1: Standard for Loop with Counter
This is the fundamental counting technique. An integer variable count is
initialized to 0. A for loop iterates through each word in the colors list. An if
statement checks if the word is equal to the target. If the condition is true,
the counter count is incremented by 1.
Method 2: List Comprehension and sum()
This elegant method uses a list comprehension to generate a sequence of
1s for every element in colors that equals the target. For every word that is
equal to "Violet", the comprehension yields a 1. The built-in sum() function
then adds up all these 1s, giving the total count of the target word.
Method 3: map() and sum() with a lambda function
This functional programming approach uses the map() function along with
a lambda function. The lambda function checks if an element x is equal to
the target, returning True or False. The map() function applies this check to
every element in the colors list, resulting in a sequence of True and False
boolean values. When sum() is applied to this sequence, True is treated as 1
and False as 0, effectively counting the occurrences of True (i.e., the target
word). A much simpler and built-in Python approach is [Link](target).
Question 9: Create a dictionary from two lists: one with names and
one with ages
The task is to pair elements from the names list and the ages list to form a
dictionary where names are keys and ages are values.
Method 1: Standard for Loop with Index
This method uses a traditional for loop that iterates over the indices of one
of the lists using range(len(names)). Inside the loop, it uses the index i to
simultaneously access the corresponding element from the names list
(names[i]) for the key and the ages list (ages[i]) for the value, and assigns
them to the new students_dict.
Method 2: Dictionary Comprehension with Index
This method uses a dictionary comprehension which is a more compact
syntax for the logic in Method 1. It iterates over the indices i using
range(len(names)) and constructs the dictionary using the key-value pair
expression {names[i]: ages[i]}.
Method 3: zip() and dict() Constructor
This is the most Pythonic and recommended way. The built-in zip()
function takes the two lists and iterates over them simultaneously, creating
a sequence of tuples where each tuple contains one name and one age. The
built-in dict() constructor then takes this sequence of two-item tuples and
automatically converts it into a dictionary where the first item of each tuple
becomes the key and the second becomes the value.
Question 10: Loop through a dictionary and print each key-value
pair
The goal is to iterate through the stud_dict_sample dictionary and print both
the student name (key) and the age (value).
Method 1: Looping over Keys and Indexing (for key in students:)
This method iterates directly over the dictionary, which yields the keys. For
each key, the corresponding value is retrieved using the square bracket
notation: students[key]. Both the key and value are then printed. This is a
common and simple method.
Method 2: items() Method
This is the most direct and recommended method for iterating over both
keys and values simultaneously. The built-in items() method returns a view
of the dictionary's key-value pairs as a sequence of tuples. The for loop
immediately unpacks each tuple into two variables, key and value, which
are then printed.
Method 3: zip() with keys() and values()
This method first calls the keys() method and the values() method to get
separate views of the keys and values. It then uses the zip() function to
combine them into pairs, which are then unpacked into key and value for
printing. While correct, it's less direct than using the items() method.
Method 4: enumerate() with items() and F-string
This method builds upon Method 2 by adding a 1-based index to the output.
It uses the items() method (for key-value pairs) and wraps it with the
enumerate() function (starting at 1). enumerate provides an index idx and
the key-value tuple, which is unpacked into key and value. The final output is
formatted neatly using an f-string to include the index, key, and value.