CodingNic

Python Lists

List Exercises

Python Lists 20 min read

List Exercises

Objectives

This chapter introduces no new concepts. It’s a chance to put list basics, iteration, and comprehension together. Complete every exercise using list comprehension.

Exercises

  1. Given the list [1, 2, 3, 4], print out all the values in the list.
  2. Given the list [1, 2, 3, 4], print out all the values multiplied by 20.
  3. Given the list ["Erin", "Jordan", "Maya"], return a new list with only the first letter of each name (["E", "J", "M"]).
  4. Given the list [1, 2, 3, 4, 5, 6], return a new list of just the even values ([2, 4, 6]).
  5. Given the lists [1, 2, 3, 4] and [3, 4, 5, 6], return a new list that is the intersection of the two ([3, 4]).
  6. Given the list ["Erin", "Jordan", "Maya"], return a new list with each word reversed and lowercased (['nire', 'nadroj', 'ayam']).
  7. Given the strings "first" and "third", return a new list of every letter present in both words (["i", "r", "t"]).
  8. For all the numbers between 1 and 100, return a list of every number divisible by 12 ([12, 24, 36, 48, 60, 72, 84, 96]).
  9. Given the string "amazing", return a list with all the vowels removed (['m', 'z', 'n', 'g']).
  10. Using a nested list comprehension (the repetition pattern from the previous lesson: [some_list for _ in range(n)]), build a list containing 3 copies of [0, 1, 2]. The result should be [[0, 1, 2], [0, 1, 2], [0, 1, 2]].
  11. Using the same technique, build a list containing 10 copies of list(range(10)), that is, a list of 10 inner lists, each one being [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].

Recap

You can now build and modify lists, loop over them (with for, while, enumerate, range), and write list comprehensions to do all of it more concisely. That’s the toolkit Module 2 set out to build.

Next module: dictionaries, Python’s key-value data structure.