Iterators परिचय

Python टूलबॉक्स

Hugo Bowne-Anderson

Data Scientist at DataCamp

for लूप से iteration

  • हम for लूप से list पर iterate कर सकते हैं
employees = ['Nick', 'Lore', 'Hugo']

for employee in employees: print(employee)
Nick
Lore
Hugo
Python टूलबॉक्स

for लूप से iteration

  • हम for लूप से string पर iterate कर सकते हैं
for letter in 'DataCamp':
    print(letter)
D
a
t
a
C
a
m
p
Python टूलबॉक्स

for लूप से iteration

  • हम for लूप से range object पर iterate कर सकते हैं
for i in range(4):
    print(i)
0
1
2
3
Python टूलबॉक्स

Iterators बनाम iterables

  • Iterable
    • उदाहरण: lists, strings, dictionaries, file connections
    • ऐसा object जिसके साथ iter() method जुड़ा हो
    • किसी iterable पर iter() लगाने से iterator बनता है
  • Iterator
    • next() से अगला मान देता है
Python टूलबॉक्स

Iterables पर next() से iterate करना

word = 'Da'
it = iter(word)

next(it)
'D'
next(it)
'a'
next(it)
StopIteration                   Traceback (most recent call last)
<ipython-input-11-2cdb14c0d4d6> in <module>()
-> 1 next(it)
StopIteration:
Python टूलबॉक्स

एक साथ iterate करना: *

word = 'Data'
it = iter(word)

print(*it)
D a t a
print(*it)
  • अब और मान नहीं बचे!
Python टूलबॉक्स

Dictionaries पर iteration

pythonistas = {'hugo': 'bowne-anderson', 'francis': 'castro'}

for key, value in pythonistas.items(): print(key, value)
francis castro
hugo bowne-anderson
Python टूलबॉक्स

File connections पर iteration

file = open('file.txt')
it = iter(file)

print(next(it))
This is the first line.
print(next(it))
This is the second line.
Python टूलबॉक्स

अभ्यास करते हैं!

Python टूलबॉक्स

Preparing Video For Download...