A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-iter-method/ below:

Python iter() method - GeeksforGeeks

Python iter() method

Last Updated : 11 Dec, 2024

Python iter() method is a built-in method that allows to create an iterator from an iterable. An iterator is an object that enables us to traverse through a collection of items one element at a time. Let’s start by understanding how iter() works with a simple example.

Python
a = [10, 20, 30, 40]

# Convert the list into an iterator
iterator = iter(a)

# Access elements using next()
print(next(iterator))  
print(next(iterator))  
Syntax of iter() method

iterator = iter(iterable)

Parameters

Return Type

Examples of iter() Method Using iter() with String Python
# Convert string to iterator
s = "Python"
iterator = iter(s)

print(next(iterator))  
print(next(iterator))  
Using iter() with Dictionary Python
d = {'a': 1, 'b': 2, 'c': 3}
iterator = iter(d)

for key in iterator:
    print(key)  
Using iter() with Callable and Sentinel Python
# Generate numbers until sentinel value is encountered
import random

iterator = iter(lambda: random.randint(1, 5), 3)
for num in iterator:
    print(num)


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4