Tuple unpacking in Python

With the typical list-based for-loop in Python, we don’t use indexes:

foods = ["bread", "milk", "eggs"]
for food in foods:
   print(food)

But if we also need the index number for each list item (which does, of course, exist):

foods = ["bread", "milk", "eggs"]
for i, food in enumerate(foods):
   print( str(i) + ": " + food )

I learned that today from this 25-minute video about loops in Python (also covers while-loops):

Tuple unpacking is explained at 11:58 in the video. It’s what makes enumerate() possible.

(PyCon 2017)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

css.php