Hacker News new | ask | show | jobs
by pdonis 4603 days ago
my proposal is more explicit

One could just as easily say that your proposal is less explicit, because a sequence is a sequence of items, not (index, item) tuples, yet you're making the "for" iteration yield tuples.

Similarly, a dict is a container of keys, not (key, value) pairs. The reason is that otherwise you would be unable to check to see if a key was in the dict unless you knew the value that went with it: but in that case why would you need the dict? (Technically, you could still iterate over the entire dict looking for your key, but that's extremely slow; the whole point of having a dict is to be able to do fast lookups of keys in order to retrieve their values.)

Writing .items() or surrounding enumerate() does not make your code look prettier, does it?

Neither does having to extract just one item from a tuple when I don't need the index. There's no way around the fact that one of the types of iteration (either just items, or index, item tuples) is going to have to be spelled with something extra. So just saying "I shouldn't have to type something extra" isn't a sufficient argument. You need to justify why your preferred type of iteration should be the one with the shorter spelling: and since your preferred type of iteration has extra baggage attached to it, it seems perfectly legitimate to me that it should have the longer spelling, not the shorter one.

find the location of a specific item in the list

That's what the "index" method is for.

1 comments

I forget if it's Jinja or Django's template, but one of them has a function that only exists inside of for loops that returns the current index. I thought that was a great way to handle it, since it's always available without changing any syntax.

In retrospect, I suppose the .index() method would be fine, since Lists can't hold two of the same object, and Dicts return the key by default.

Lists can't hold two of the same object

Yes, they can. Try it! The index method has extra arguments to let you specify a range of indexes in the list to search, so you can find multiple indexes that point to the same object (by picking a range that excludes indexes you've previously found).

Dicts return the key by default

Dicts don't have an index method; dict keys are not ordered.