How to use 'iterable python' in Python

Every line of 'iterable python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
12def isiterable(obj):
13 """Returns `True` if the given object is iterable."""
14 try:
15 iter(obj)
16 return True
17 except TypeError:
18 return False
6def is_iterable(obj):
7 """
8 Robustly test whether an object is iterable.
10 Parameters
11 ----------
12 obj : object
13 The object to be checked.
15 Returns
16 -------
17 is_iterable : boolean
18 `True` if the object is iterable, `False` otherwise.
20 Notes
21 -----
22 This test iterability by calling `iter()` and catching a `TypeError`.
23 Various other ways might occur to you, but they all have flaws:
25 * `hasattr(obj, '__len__')` will fail for objects that can be iterated
26 on despite not knowing their length a priori.
27 * `hasattr(obj, '__iter__')` will fail on objects like Theano tensors
28 that implement it solely to raise a `TypeError` (because Theano
29 tensors implement `__getitem__` semantics, Python 2.x will try
30 to iterate on them via this legacy method if `__iter__` is not
31 defined).
32 * `hasattr` has a tendency to swallow other exception-like objects
33 (`KeyboardInterrupt`, etc.) anyway, and should be avoided for this
34 reason in Python 2.x, but `getattr()` with a sentinel value suffers
35 from the exact same pitfalls above.
36 """
37 try:
38 iter(obj)
39 except TypeError:
40 return False
41 return True

Related snippets