Menu
Coddy logo textTech

Access Items

Lesson 3 of 11 in Coddy's Sets in Python course.

In Python, unlike lists or tuples, sets do not support direct indexing or slicing. However, you can loop through the items or check if an item exists in the set.

  1. Looping Through a Set:

    You can use a for loop to iterate through all the items in a set. Since sets are unordered, the items will be returned in an arbitrary order.

    fruits = {"apple", "banana", "cherry"}
    for fruit in fruits:
    	print(fruit)
  2. Checking for Existence:

    You can use the in keyword to check if an item exists in a set. This is a fast and efficient way to test for membership.

    fruits = {"apple", "banana", "cherry"}
    print("banana" in fruits)  # Output: True
    print("orange" in fruits)  # Output: False

While you cannot access items in a set directly using an index, these methods provide flexible ways to work with the elements in a set.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

challenge icon

Challenge

Easy

You are given a set, loop through it, and print every item in it.

Try it yourself

my_set = {"apple", "banana", "cherry", "date", "elderberry"}

All lessons in Sets in Python