4/26/2020

Idiomatic Python

Idiomatic Python gists.
  • Loop a list with index:
  • 
    for index, value in enumerate([1, 2, 3, 4, 5]):
        print("%s -> %s" % (index, value))
    
    
  • Loop a dictionary's key-value pairs:
  • 
    for key, value in {1: 'one', 2: 'two', 3: 'three'}.items():
        print("%s -> %s" % (key, value))
    
    
  • Loop backward a list:
  • 
    for value in reversed([1, 2, 3, 4, 5]):
        print(value)
    
    
  • Loop backward a list with index:
  • 
    for index, value in reversed([i for i in enumerate([1, 2, 3, 4, 5])]):
        print("%s -> %s" % (index, value))
    
    
  • Default dictionary - Group items with same value:
  • 
    from collections import defaultdict
    
    # group items with same value
    groups = defaultdict(list)
    
    for value in [1,1,2,2,3,3]:
        groups[value].append(n)