Practice: Introduction to Lists
Q1. First and last
Given nums = [4, 8, 15, 16, 23, 42], print the first and last items on separate lines.
Goal: Practise this chapter topic.
Q2. Count the items
Create a list of four city names and print how many items it has.
Goal: Practise this chapter topic.
Q3. Change an item
Given pets = ["cat", "dog", "fish"], replace dog with rabbit and print the list.
Goal: Practise this chapter topic.
Q4. Sum with a loop
Use a for loop to add up the items of [3, 5, 7, 9] and print the total.
Goal: Practise this chapter topic.
Q5. Even numbers only
Print every even number from [1, 2, 3, 4, 5, 6], one per line.
Goal: Practise this chapter topic.
Q6. Build a list of squares
Start with an empty list and append the squares of 1 to 5. Print the list.
Goal: Practise this chapter topic.
Q7. Largest and smallest
For [14, 3, 99, 27] print the largest and smallest on one line separated by a space.
Goal: Practise this chapter topic.
Q8. Negative index
What does this print?
letters = ["a", "b", "c"]
print(letters[-1])Goal: Practise this chapter topic.
Q9. Append result
What does this print?
a = [1, 2]
print(a.append(3))Goal: Practise this chapter topic.
Q10. Alias effect
What does this print?
a = [1, 2, 3]
b = a
b.append(9)
print(a)Goal: Practise this chapter topic.
Q11. Copy effect
What does this print?
a = [1, 2, 3]
b = a.copy()
b.append(9)
print(a)Goal: Practise this chapter topic.
Q12. Sorted keeps original
What does this print?
nums = [3, 1, 2]
print(nums)
print(sorted(nums))Goal: Practise this chapter topic.
Q13. Membership
What does this print?
fruits = ["apple", "kiwi"]
print("kiwi" in fruits)
print("plum" in fruits)Goal: Practise this chapter topic.
Q14. Index error
This code should print the last item but crashes with IndexError. Fix it.
items = ["x", "y", "z"]
print(items[len(items)])Goal: Practise this chapter topic.
Q15. Assigning append
After this code, nums is None instead of a list. Fix it.
nums = [1, 2]
nums = nums.append(3)
print(nums)Goal: Practise this chapter topic.
Q16. Lists vs strings
Name two differences between a list and a string.
Goal: Practise this chapter topic.
Q17. Why copy()?
Why do we need copy() when b = a already exists?
Goal: Practise this chapter topic.
Q18. Average mark
Marks are [70, 80, 90, 100]. Print the average.
Goal: Practise this chapter topic.
Q19. Shopping cart
Start with cart = ["milk"], add bread and eggs, remove milk, then print the cart.
Goal: Practise this chapter topic.