callable() / iter() / next()
| Since: | Python 2(2000) |
|---|
Built-in functions for checking whether an object is callable, creating iterators, and manually retrieving elements from them.
Syntax
# Checks whether an object is callable (a function, class, etc.). callable(object) # Creates an iterator from an iterable. iter(object) iter(callable_object, sentinel) # Returns the next element from an iterator. next(iterator, default) # Returns the hash value of an object. hash(object)
Function List
| Function | Description |
|---|---|
| callable(obj) | Returns True if the object is callable. Applies to functions, classes, and objects that define __call__. |
| iter(obj) | Creates an iterator from an iterable object. In the two-argument form, it calls the callable repeatedly until the sentinel value is returned. A sentinel value is a special value that signals the end of a repeated operation. |
| next(iterator, default) | Returns the next element from the iterator. When there are no more elements, returns default if specified; otherwise raises StopIteration. |
| hash(obj) | Returns the hash value (an integer) of an object. Only objects usable as dictionary keys or set members are supported. |
Sample Code
sample_callable_iter_next.py
# Use callable() to check whether an object is callable.
def greet():
return "Hello"
print(callable(greet)) # True (functions are callable)
print(callable(42)) # False (integers are not callable)
print(callable(str)) # True (classes are callable)
print(callable(print)) # True (built-in functions are also callable)
# Objects that define __call__ are also callable.
class Multiplier:
def __init__(self, factor):
self.factor = factor
def __call__(self, x):
return x * self.factor
triple = Multiplier(3)
print(callable(triple)) # True
print(triple(5)) # 15
# Use iter() and next() to iterate over a list manually.
members = ["Okabe Rintaro", "Makise Kurisu", "Shiina Mayuri"]
it = iter(members)
print(next(it)) # Okabe Rintaro
print(next(it)) # Makise Kurisu
print(next(it)) # Shiina Mayuri
# print(next(it)) # Raises StopIteration.
# Specifying a default value prevents an exception from being raised.
it2 = iter(members)
print(next(it2, "none")) # Okabe Rintaro
print(next(it2, "none")) # Makise Kurisu
print(next(it2, "none")) # Shiina Mayuri
print(next(it2, "none")) # none (no more elements)
# Two-argument form of iter(): calls the function repeatedly until the sentinel value is returned.
import random
# Simulated dice: keeps rolling until a 6 appears.
rolls = list(iter(lambda: random.randint(1, 6), 6))
print(f"Rolled {len(rolls)} time(s) before getting a 6.")
# Use hash() to check the hash value of an object.
print(hash("hello")) # Hash value of a string (varies between runs)
print(hash(42)) # 42 (integer hash values often equal the integer itself)
print(hash((1, 2, 3))) # Tuples are hashable.
# print(hash([1, 2, 3])) # TypeError: lists are not hashable.
python3 callable_iter_next.py True False True True True 15 Okabe Rintaro Makise Kurisu Shiina Mayuri Okabe Rintaro Makise Kurisu Shiina Mayuri none Rolled 4 time(s) before getting a 6. 8015029652457857303 42 3258844298692914498
Notes
Python's for loop internally calls iter() to create an iterator, then repeatedly calls next() until StopIteration is raised, at which point the loop ends. Understanding this mechanism makes it easier to grasp how generators and custom iterators work.
If you do not specify a default value for next(), calling it on an exhausted iterator will raise a StopIteration exception. When using next() outside of a loop, always specify a default value or catch the exception with a try-except block.
hash() cannot be used on mutable objects such as lists or dictionaries. Only hashable (immutable) objects can be used as dictionary keys or set members. To enable hashing in a custom class, implement the __hash__() method. For iterating over files, see open().
If you find any errors or copyright issues, please contact us.