Iterables in Python

An iterable is an object that can be iterated over, i.e. it can be used in a for loop. Examples of iterables include lists, tuples, and dictionaries.

When you create a list, you can access each element in the list by its index.

For example:

my_list = [1, 2, 3]
for i in my_list:
    print(i) 1 2 3

Tuples are similar to lists, but they are immutable, meaning they cannot be changed. You can access each element in a tuple by its index, just like with a list:

my_tuple = (1, 2, 3)
for i in my_tuple:
    print(i) 1 2 3

Dictionaries are another type of iterable. They are made up of key-value pairs. You can access each value in a dictionary by its key.

For example:

my_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

for key, value in my_dict.items():
    print(key, value)

# key1 value1
# key2 value2
# key3 value3

How do you create an iterable in python?

One way to make a class iterable is to define an __iter__ method on the class that returns an iterator.

For example:

class Foo:
    def __iter__(self):
        return iter(range(10))

Another way is to define a __getitem__ method that behaves like a list or tuple, allowing the class to be subscripted.

For example:

class Foo:
    def __getitem__(self, index):
        return index

In both cases, the class can then be used in a for loop:

for i in Foo():
    print(i)

# 0
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
Previous
Previous

How to find the longest non-repeating substring in a string with python

Next
Next

What is a Binary Tree and how do you create one in Python?