[Tutor] List index usage: is there a more pythonesque way?

spir ☣ denis.spir at gmail.com
Mon Apr 19 09:26:06 CEST 2010


On Mon, 19 Apr 2010 00:37:11 +0100
C M Caine <cmcaine at googlemail.com> wrote:

> That's two new things I've learnt. I didn't realise that for loops
> could be used like that (with more than one... key?).

Consider considering things differently: a for loop always iterates over items of a collection you indicate:

l = [1,2,3]
# item is list item		(implicit, it could be written items(l) or l.items())
for n in l: print n,
# item is (index,item) pair
for (i,n) in enumerate(l): print (i,n),
print

d = {'a':1, 'b':2, 'c':3}
# item is dict key		(implicit, it could be written d.keys())
for k in d: print k,
# item is dict value
for v in d.values(): print v,
# item is (key,value) pair
for (k,v) in d.items(): print (k,v),
print

(In the last case "items()" is maybe a bit confusing.)

Python lets you construct your own iterators on custom collections to iterate in a different way:
class NestedList(list):
	def __iter__(self):
		ll = list.__iter__(self)
		for l in ll:
			for item in l:
				yield item
ll = NestedList([[1,2,3], [9,8]])
for n in ll: print n,

Denis
________________________________

vit esse estrany ☣

spir.wikidot.com


More information about the Tutor mailing list