YouTip LogoYouTip

Python3 Func Iter

# Python 3 iter() Function The `iter()` function is a built-in Python function used to convert an iterable object into an iterator. Iterators are a fundamental concept in Python's iteration protocol. By using `iter()`, you can obtain an iterator from any compatible iterable object (such as lists, tuples, or strings) and then retrieve its elements one by one using the `next()` function. --- ## Syntax and Parameters The `iter()` function supports two distinct signatures depending on how it is called: ### Syntax Format ```python iter(object) iter(object, sentinel) ``` ### Parameter Description * **`object`**: * **Type**: Iterable or Callable. * **Description**: * In the single-argument form (`iter(object)`), this must be an iterable object supporting the iteration protocol (implementing the `__iter__()` method), or a sequence protocol (implementing the `__getitem__()` method with integer arguments starting at `0`). * In the two-argument form (`iter(object, sentinel)`), this must be a callable object (such as a function or method) that takes no arguments. * **`sentinel`** (Optional): * **Type**: Any value. * **Description**: A sentinel value used to signal the end of iteration. When the value returned by the callable `object` equals this `sentinel` value, iteration stops immediately, raising a `StopIteration` exception. ### Return Value * Returns an **iterator** object. * **Key Characteristic**: Iterators can only move forward. Once an element is consumed, you cannot go backward. --- ## Code Examples ### Example 1: Basic Usage (Single-Argument Form) This example demonstrates how to convert a standard Python list into an iterator and retrieve its elements. ```python # Create an iterator from a list my_list = [1, 2, 3] iterator = iter(my_list) # Retrieve elements using next() print(next(iterator)) # Output: 1 print(next(iterator)) # Output: 2 print(next(iterator)) # Output: 3 # Calling next() again will raise a StopIteration exception # print(next(iterator)) # Iterators can also be traversed using a for loop my_list = [1, 2, 3] for item in iter(my_list): print(item, end=" ") # Output: 1 2 3 ``` **Expected Output:** ```text 1 2 3 1 2 3 ``` **Code Analysis:** 1. `iter(my_list)` converts the list into an iterator object. 2. An iterator can only be traversed once. Once it is exhausted (i.e., raises `StopIteration`), you must create a new iterator to traverse the collection again. --- ### Example 2: Creating Iterators from Strings and Tuples The `iter()` function works seamlessly with other built-in sequence types like strings and tuples. ```python # String iterator s = "hello" string_iterator = iter(s) print(next(string_iterator)) # Output: h print(next(string_iterator)) # Output: e print(next(string_iterator)) # Output: l # Tuple iterator t = (1, 2, 3) tuple_iterator = iter(t) print(next(tuple_iterator)) # Output: 1 print(next(tuple_iterator)) # Output: 2 ``` **Expected Output:** ```text h e l 1 2 ``` **Code Analysis:** * A string iterator yields one character at a time. * A tuple iterator yields one element at a time. --- ### Example 3: Using the `sentinel` Parameter The two-argument form of `iter(callable, sentinel)` is highly useful for reading data streams or generating values until a specific "stop" condition is met. In this example, we define a custom reader class and use a `lambda` function as the callable argument. The iterator will continuously call the lambda function until it returns the sentinel value `"END"`. ```python class ReadUntil: def __init__(self, data, stop_at): self.data = data self.stop_at = stop_at self.index = 0 def get_next_item(self): """A callable method that returns the next item or 'END'""" if self.index >= len(self.data): return "END" value = self.data[self.index] self.index += 1 return value # Sample data containing a sentinel marker data = ["a", "b", "c", "END", "d"] reader = ReadUntil(data, "END") # Create an iterator that calls reader.get_next_item until it returns "END" iterator = iter(reader.get_next_item, "END") for item in iterator: print(item, end=" ") ``` **Expected Output:** ```text a b c ``` **Code Analysis:** * `iter(reader.get_next_item, "END")` takes a callable (`reader.get_next_item`) and a sentinel value (`"END"`). * Each iteration step calls `get_next_item()`. When the returned value matches `"END"`, the iterator automatically raises `StopIteration` to terminate the loop, excluding the sentinel value itself from the output. --- ## Key Considerations 1. **One-Way Traversal**: Iterators are stateful and can only move forward. Once you consume an item from an iterator, it is gone. 2. **Memory Efficiency**: Iterators evaluate elements lazily (on-demand). This makes them highly memory-efficient when dealing with large datasets or infinite streams compared to loading entire lists into memory. 3. **The Sentinel Requirement**: When using the two-argument form `iter(object, sentinel)`, the first argument **must** be a callable object. Passing a non-callable object will raise a `TypeError`.
← Python3 Func PropertyPython3 Func Super β†’