Looping techniques in Python

Python has multiple techniques for looping over data structures. Dictionary looping with both key and value can be done using the items() method: my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): print(k, v) # first a # second b The enumerate() function allows looping with both index and value through any sequence: my_list = ['a', 'b'] for i, v in enumerate(my_list): print(i, v) # 0 a # 1 b zip() function can be used to pair two or more sequences in order to loop over both of them in parallel:...

May 4, 2017 · 1 min · Rezha Julio

Enhance your tuples

Standard Python tuples are lightweight sequences of immutable objects, yet their implementation may prove inconvenient in some scenarios. Instead, the collections module provides an enhanced version of a tuple, namedtuple, that makes member access more natural (rather than using integer indexes). Import namedtuple: from collections import namedtuple Create a namedtuple object: point = namedtuple('3DPoint', 'x y z') A = point(x=3, y=5, z=6) print(A) # 3DPoint(x=3, y=5, z=6) Access a specific member:...

May 3, 2017 · 1 min · Rezha Julio

Get more with collections!

In addition to Python’s built-in data structures (such as tuples, dicts, and lists), a library module called collections provides data structures with additional features, some of which are specializations of the built-in ones. Import the module: import collections Specialized container datatypes are usually dict subclasses or wrappers around other classes like lists, tuples, etc. Notable implementations are : the Counter class used for counting hashable objects. defaultdict class used as a faster implementation of a specialised dictionary....

May 2, 2017 · 1 min · Rezha Julio

There is more to copying

An assignment only creates a “binding” (an association) between a name and a “target” (object of some type). A copy is sometimes necessary so you can change the value of one object without changing the other (when two names are pointing to the same object). # Assignment: bind the name y to # the list [1, 2]. y = [1, 2 ] # Create another binding - # bind the name x to the same # object that y is currently bound to....

May 1, 2017 · 1 min · Rezha Julio

Implementing weak references in Python

Normal Python references to objects increment the object’s reference count thus preventing it from being garbage collected. If a user desires creating weak references, the weakref module can be used: import weakref class Rezha(object): pass To create a weak reference, the ref class is used: # object instance rezha = Rezha() # weak reference to our object r = weakref.ref(rezha) Then, you can call the reference object: print(r) # <weakref at 0x01414E40; to 'Rezha'....

April 30, 2017 · 1 min · Rezha Julio