List drills
Drills to practice working with lists in Python.
Basics
Solve the below tasks and state their time and space complexities.
Define a list.
A list is a finite, ordered, and mutable sequence of elements.
Create a list a
containing the letters a, b, and c.
|
|
Append z.
|
|
Insert x at the second position.
|
|
Append the characters m, n.
|
|
Remove the first occurrence of x from the list.
|
|
Remove the second to last element from the list.
|
|
Remove and return the last item.
|
|
Remove and return the second item.
|
|
Check whether c is in the list.
|
|
Return the index of c.
|
|
Count occurrences of ‘c’.
|
|
Sort the list in place.
|
|
Insert ‘z’ in the first position.
|
|
Replace the just inserted z with ‘k’
|
|
Create a sorted copy of the list.
|
|
Reverse the order in place.
|
|
Create a reversed iterator.
|
|
Delete all elements from the list.
|
|
Deep and shallow copies
|
|
Create shallow copies b
, c
, d
, and e
of a
, all in different ways.
|
|
Check that the new lists are indeed shallow copies.
|
|
True
Create a deep copy e
of a
.
|
|
Check that the new list is a deep copy.
|
|
List comprehensions
|
|
Reproduce the output of the below using a list comprehension.
results = []
for color in colors:
for size in sizes:
results.append((color, size))
results
|
|
Create a copy of results
sorted by size in ascending order.
|
|
Summing elements
|
|
Sum a
using the built-in method.
|
|
Sum the list using a recursive algorithm.
|
|
8
Sum the list using a for loop.
|
|
Sum the list using a while loop without altering the input.
|
|
Misc.
What is c
?
|
|
[1, 2]
Find the indices of the min and max elements in the list below.
|
|
|
|
Removing duplicates
Write an algorithm to remove duplicates from a list while maintaining it’s original order (from Python cookbook recipe 1.10).
|
|
Use a generator function to achieve the same.
|
|
Remove duplicates from the below sorted list by updating the original list
|
|
|
|
[1, 2, 3, 4, 5, 6, 7]
Implementing a stack
Implement a stack with push()
, pop()
, peek()
, and is_empty()
methods.
|
|
## Implementing a queue
Implement a queue with basic operations enqueue()
, dequeue()
, and is_empty()
.
|
|