TECHNOLOGIESTieInn Technologies

Lists, dictionaries, and comprehensions

Python · 18 questions

Short notes

Key idea

Lists hold items in order; dictionaries map keys to values. Comprehensions build a new list or dict from an old one in one line.

Syntax

nums = [3, 1, 4]
nums.append(1); nums[0]; nums[-1]; nums[1:3]; len(nums)

price = {"pen": 10, "book": 120}
price["pen"]; price.get("bag", 0); price["bag"] = 500
for name, p in price.items(): ...

[x * 2 for x in nums if x > 1]
{k: v for k, v in price.items() if v > 50}

Example

Count how many orders each city has:

cities = ["Chennai", "Madurai", "Chennai"]
counts = {}
for c in cities:
    counts[c] = counts.get(c, 0) + 1
print(counts)   # {'Chennai': 2, 'Madurai': 1}

Traps

  • Indexes start at 0; nums[3] on a 3-item list is an error.
  • d["missing"] raises KeyError; use .get() when the key may not exist.
  • b = a doesn't copy a list. Both names point to the same list; use a.copy().
  • Slices stop before the end index: nums[1:3] is items 1 and 2.

Want the full lesson with step-by-step examples, a project and a certificate? Python course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    Lists, dictionaries, and comprehensions

  1. Question 1easy

    price = {'Earbuds': 1999}. Which line returns 0 instead of raising an error for a missing key?

  2. Lists, dictionaries, and comprehensions

  3. Question 2medium

    What does this print?

    a = [1, 2, 3]
    b = a
    b.append(4)
    print(len(a))
  4. Lists, dictionaries, and comprehensions

  5. Question 3easy

    What does this print?

    q = [5, 1, 2, 3, 2]
    print(q[-1] + sum(q[1:3]))
  6. Lists, dictionaries, and comprehensions

  7. Question 4medium

    What does this print?

    cities = ["Chennai", "Kochi", "Chennai", "Pune", "Kochi"]
    print(len(set(cities)))
  8. Lists, dictionaries, and comprehensions

  9. Question 5easy

    What does this print?

    cities = ["Chennai", "Madurai", "Pune"]
    print(cities[1])

13 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.