Python Collections: Lists, Tuples, Sets, and Dictionaries

Lists

A list is an ordered, mutable collection. Lists can contain any type of element and allow duplicates.

You can:

  • Access elements by index: my_list[0]
  • Append items: my_list.append("new")
  • Insert at a position: my_list.insert(1, "inserted")
  • Remove an item: my_list.remove("apple")
  • Pop the last item: my_list.pop()
  • Sort the list: my_list.sort()
  • Join lists: list1 + list2 or list1.extend(list2)
  • Nested lists: lists inside other lists for complex data
Loading...
Output:

Tuples

A tuple is like a list, but it is immutable (cannot be changed).

You can:

  • Access elements by index: my_tuple[0]
  • Join tuples: new_tuple = t1 + t2
  • Unpack tuples into variables: a, b = (1, 2)
  • Check length: len(my_tuple)
  • Count values: my_tuple.count(value)
Loading...
Output:

Sets

A set is an unordered collection of unique elements.

You can:

  • Add elements: my_set.add(x)
  • Remove elements: my_set.remove(x) or discard(x)
  • Check membership: x in my_set
  • Set operations: union, intersection, difference, etc.
Loading...
Output:

Dictionaries

A dictionary is a collection of key-value pairs. Keys must be unique.

You can:

  • Access values: student["name"]
  • Update values: student["age"] = 21
  • Add key-value pairs: student["grade"] = "A"
  • Remove pairs: student.pop("age")
  • Loop through keys and values: for k, v in student.items()
Loading...
Output:

Practice: Combine It All

Prompt: Create a program that stores a list of students. Each student is a dictionary with keys name and grades (a list). Then, print the average grade for each student.

Target Output:

Alice: 87.5
Bob: 91.5
Loading...
Output:

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic