How do I check if a value is iterable in Python?
Benjamin C
benjamin c profile pic

To check if a value is iterable in Python, you can use theiter() function along with a try-except block to catch theTypeError that is raised when a non-iterable object is passed to theiter() function. If the value is iterable, it means it can be iterated over using a loop or other iteration techniques. Here's an example of how you can check if a value is iterable in Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

def is_iterable(value):
    try:
   iter(value)
   return True
    except TypeError:
   return False

# Usage:
my_list = [1, 2, 3]
my_string = "Hello"
my_number = 42

print(is_iterable(my_list))  # Output: True
print(is_iterable(my_string))  # Output: True
print(is_iterable(my_number))  # Output: False

In the above code, theis_iterable() function takes avalue parameter representing the value to check for iterability. It attempts to create an iterator from the value using theiter() function. If the value can be successfully iterated over without raising aTypeError, it means the value is iterable, and the function returnsTrue. Otherwise, it catches theTypeError and returnsFalse. You can use theis_iterable() function by providing a value as an argument. It will attempt to create an iterator from the value, determining if the value is iterable. The result is then printed accordingly. It's worth noting that although most iterable objects in Python are collections like lists, tuples, sets, and strings, there are other iterable objects like generators and iterators. Therefore, this check is not limited to only collection types. This method allows you to determine if a value can be iterated over, helping you handle different types of inputs appropriately in your code.