Sunday, April 20, 2025

Python Iteration, Iter, Next

With iter() function we will target specific list, and individual next() functions will be used to print elements of list:


colors = ["red", "blue", "yellow"]

target = iter(colors)

print(next(target))
print(next(target))
print(next(target))

Result: 


red
blue
yellow
>>> 

But for loops are more practical, especially if lists are big:


colors = ["red", "blue", "yellow"]

target = iter(colors)

for x in range(3):
    print(next(target))

Result: 


red
blue
yellow
>>> 

Can we use iteration on dictionaries ? Sure:


diction = {"name" : "Anastasia", "SSN" : 246546}

target = iter(diction)

print(next(target))
print(next(target))

Result: 


name
SSN
>>> 

This is how to extract only keys, so we can put them in dedicated list:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)

for x in range(2):
    k_keys.append(next(target))

print(k_keys)

Result: 


['name', 'SSN']
>>> 

Better option is to not think about number of elements, just use len() function:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

target = iter(diction)
print("Len of diction: ", len(diction))

for x in range(len(diction)):
    k_keys.append(next(target))

print(k_keys)

Result: 


Len of diction:  2
['name', 'SSN']
>>> 

Of course, we can do that without iter() and next() functions:


diction = {"name" : "Anastasia", "SSN" : 246546}

k_keys = []

for x in diction.keys():
    print(x)

Result: 


name
SSN
>>> 

Next tutorial will be dedicated to modules.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...