python loop for while - ghdrako/doc_snipets GitHub Wiki

for item in iterable:
# the same operation goes here
from collections import namedtuple
Task = namedtuple("Task", "title description urgency")
tasks = [
Task("Homework", "Physics and math", 5),
Task("Laundry", "Wash clothes", 3),
Task("Museum", "Egypt exhibit", 4)
]

for task_i in range(len(tasks)):
  task = tasks[task_i]
  task_counter = task_i + 1
  print(f"Task {task_counter}: {task.title:<10} {task.description:<18} {task.urgency}")


# more pythonic solution
for task_i, task in enumerate(tasks, start=1):
  print(f"Task {task_i}: {task.title:<10} {task.description:<18} {task.urgency}")

The enumerate function takes an iterable and creates an iterator of the enumerate type. This iterator renders a tuple object each time: (item_counter, item) , the item’s counter, and the item from the original iterable. By default, the counter matches each item’s index, so the first item has a counter of 0. Notably, the enumerate function takes an optional argument, start , which allows you to set the number for the first item. In our case, we want to start the counting from 1, so we set start=1 in the enumerate function.

table = [12, 11, 4], [3, 22, 105], [0, 47, 31](/ghdrako/doc_snipets/wiki/12,-11,-4],-[3,-22,-105],-[0,-47,-31)
for row_index, row in enumerate(table):
  for column_index, item in enumerate(row):
    process_item(row_index, column_index, item)
>>>for i, v in enumerate(list6):
>>>  print(i, v)
0 Machine
1 Learning
2 with
3 Python
4 1.0.0

(non-Pythonic) way to do the same task:

i = 0
for v in list6:
  print (i, v)
  i += 1
for i, v in enumerate(list6, start=1):
  print(i, v)

Reversing items with reversed

for task_i in range(len(tasks)):
  task = tasks[-(task_i + 1)]
  print(f"Task: {task}")
# pythonicsolution
for task in reversed(tasks):
  print(f"Task: {task}")

The reversed function takes a sequence data object and returns a reversed object. Notably, the reversed object is an iterator that renders the items in the reverse order of the original list object.

iterables with zip

>>>list_a = [1,2,3,4]
>>>list_b = ['a','b','c','d']
>>>for item in zip(list_a,list_b):
>>>  print(item)
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
name_list = ['John', 'James', 'Jane']
phone_list = [979, 797, 897]
dict3 = dict(zip(name_list, phone_list)) # it works because here we use zip on two lists; therefore, each element of the iterable has two objects
dict3
{'John': 979, 'James': 797, 'Jane': 897}
dates = ["May 5, 2022", "May 9, 2022", "May 11, 2022"]
locations = ["School", "Home", "Downtown"]

for task_i in range(len(tasks)):
  task = tasks[task_i]
  date = dates[task_i]
  location = locations[task_i]
  print(f"{task.title}: by {date} at {location}")

for task, date, location in zip(tasks, dates, locations):
  print(f"{task.title}: by {date} at {location}")

zip object is an iterator that renders tuple objects aggregated from aligned iterables.

By default, the zip function stops zipping when the iterable with the fewest items is exhausted. If you run zip(range(3), range(4)) , for example, you only get three tuple objects. Sometimes, we want to ensure that the iterables have the same num- bers of items. To enforce such congruency, Python 3.10 introduced the optional parameter strict , which specifies that there are equal numbers of items when it’s set to True . Please note that strict is set to False by default, so previous uses of the zip function still work.

For some use cases, we want to zip until the iterable with the most items is exhausted. In these cases, we should consider using the zip_longest function, which exists in the itertools module in the standard Python library.

>>> from itertools import zip_longest
>>> list(zip_longest(range(3), range(4), range(5)))
[(0, 0, 0), (1, 1, 1), (2, 2, 2), (None, 3, 3), (None, None, 4)]

Chaining multiple iterables with chain

all_tasks = tasks + completed_tasks
for task in all_tasks:
  print(task.title)

from itertools import chain
for task in chain(tasks, completed_tasks):
  print(task.title)

Filtering the iterable with filter

for task in tasks:
  if task.urgency > 3:
  print(task)

for task in filter(lambda x: x.urgency > 3, tasks):
  print(task)

The filter function takes a function that is applied to the items of the iterable. Each item is evaluated by the function: if True , the item is kept, and if False , the item is excluded.

reversed vs reverse

When you use reversed , you create an iterator that has the same items as the iterable but in reverse order. The reverse method reverses a list object in place. The in-place change implies that this method changesthe original list object and returns None .