Skip to content

Latest commit

 

History

History
48 lines (33 loc) · 1.1 KB

cy10.md

File metadata and controls

48 lines (33 loc) · 1.1 KB

lang.py.syntax.enumarate

Loop with for loops and counters

Synopsis

  for count, value in enumerate(values):
      print(count, value)

Overview

In Python, a for loop is done over an iterable, wich means that no counter is need. But if you do want to have a variable that changes on each loop, you enumarate() instead of creating and incrementing the variable manually

Since this is an iterator, you can't acces it's itmes by indices

Cookbook

Determine the starting value of the count

Since Python sequence types are 0 based indexes, the default starting value is 0. But you can pass an argument to set the starting value of the count

  values = [a, b, c]

  for count, value in enumerate(values, start=1):
      print(count, value)

  # 1 a
  # 2 b
  # 3 c

Get the next value of an enumerate instance

You can use Python's built-in next() to get the next value of an iterator like the enumerate instance

  values = ["a", "b"]
  enum_instance = enumerate(values)
  next(enum_instance)       # (1, 'a')