Skip to content

Latest commit

 

History

History
56 lines (37 loc) · 1.48 KB

p7q9.md

File metadata and controls

56 lines (37 loc) · 1.48 KB

lang.py.type.iterable

Any object that can return its members one at a time

Overview

Iterables support the iterator protocol, wich specifies how object members are returned when an object is used in an iterator

Thera are two types and any can be used in a for loop

  • Sequences: Can be acceessed by integer indeces
  • Generators: An object that yields a value an remembers it's last state

Cookbook

Get the next value of an iterator

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

They can only iterate through an interator one time only. Once you've exahausted an iterator youw will get an StopIteration execption

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

Unpack iterables with the "*" operator

Some times you may want to unpack just a few elements and keep the rest in another variable. For that you can use the * unpacking operator.

  numbers = [3, 5, 2, 4, 7, 1]

  min_value, *rest = numbers

  print(min_value)          # 3
  print(rest)               # [5, 2, 4, 7, 1]

  for number in rest:
      if number < min_value:
        min_value = number

  print(min_value)          # 1

You may also use it to unpack elements all at once into a single variable

  li = ['Hello', 'there']
  print(*li)                # Hello there