Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
PYTHON TEXT / CHAPTER 03 / Learn / LESSON 05
Fifth class. for over a string or list yields the elements. Sometimes you also need the index.
range(n) yields 0, 1, …, n-1. It is often paired with len: for i in range(len(items)).
enumerate(items) yields (index, item) pairs. It is handy when you print both position and value:
for i, item in enumerate(items):
print(i, item)Mini example:
items = ["a", "b"]
for i in range(len(items)):
print(i)
for i, item in enumerate(items):
print(i, item)Common mistake: starting range(len(items)) from 1; or swapping enumerate order (index comes first, then the value).
Learn: indexed for via range and enumerate.
AGGREGATE IDLE
›