9.05.2006

Pythonic Discoveries, Part 2

While working on the feed parsing program, I wanted to display a numbered list. In C++, I would have used an incrementing variable and thought nothing of it. But I found this a little more complicated in Python. When I tried to simply set a variable and then display it along with an item in the list I was iterating through, I got an error that an int and a string cannot be concatenated. So I ended up doing it thus:

entrylist = []
for entry in current.entries:
entrylist.append(entry.title)
bullet = 1
for x in entrylist:
print str(bullet) + "- " + x
bullet+=1
I don't know if this was a bad hack, and if there is an easier way to do this, but it worked. It seem interesting that an increment operator is not built into Python.\

2 comments:

Anonymous said...

As you have discovered list comprehensions, your first for loop is more Pythonically expressed:

entrylist = [entry.title for entry in current.entries]

You've also found how to iterate over a list, but there is a builtin called enumerate that will let you iterate over a list, giving (index,item) pairs for each item (see also how to create output using string interpolation):

for bullet, x in enumerate(entrylist):
print "%d - %s" % (bullet,x)

Paul

Immortal Curiosity said...

I actually didn't know you could setup for loops in the list creation. It is much more elegant.

enumerate was indeed the function I was looking for. I foolishly said there was no iteration built into Python based on the searching I had done for a related function online.

Thanks for the help!