Open In App

Python iter() method

Last Updated : 11 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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))  

Output
10
20

Syntax of iter() method

iterator = iter(iterable)

Parameters

  • iterable: Any object capable of returning its elements one at a time. Examples include lists, tuples, dictionaries, and strings.

Return Type

  • Returns an iterator object that can be used with the next() function or a for loop to access the elements sequentially.

Examples of iter() Method

Using iter() with String

Python
# Convert string to iterator
s = "Python"
iterator = iter(s)

print(next(iterator))  
print(next(iterator))  

Output
P
y

Using iter() with Dictionary

Python
d = {'a': 1, 'b': 2, 'c': 3}
iterator = iter(d)

for key in iterator:
    print(key)  

Output
a
b
c

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)

Output
5
5

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy