/ Published in: Python
When is it appropriate to use dict.items() vs dict.iteritems?
Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?
Also, when is it appropriate to use range() vs xrange(). From my
understanding, xrange() essentially gives you an iterator across a
range, so it should be used when iterating. Should you only use
range() when want to physically store the range as a list?
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# Both seem to work for something like: mydict = {'a' : 1, 'b' : 2} for key,val in mydict.items(): print key,val # ==> a 1 b 2 for key,val in mydict.iteritems(): print key,val # ==> a 1 b 2 # iteritems and xrange only provide values when requested. # items and range build complete list when called. # Both work, you may prefer xrange/iteritems for iteration on large # collections, you may prefer range/items when processing of the result # value explicitly need a list (ex. calculate its length) or when you are # going to manipulate the original container in the loop.