Why increase writing

Why:
tmp = {1:2, 2:3}
fot i in tmp.keys():

Became:
tmp = {1:2, 2:3}
fot i in list(tmp.keys()):

Is there any explanation at all to do something more complicated?
Just don’t tell me it’s for productivity. We all know that every new language is slower than the old ones. Those with productivity, explain them to advertising agents

I don’t know. Why did it? The existing way still works (as long as you spell for correctly). So does this:

tmp = {1:2, 2:3}
for i in tmp:

So why create the list unnecessarily? I don’t know. More context needed.

3 Likes

If you mean “why do I have to change the code?”, the answer is you don’t - for i in tmp.keys(): works perfectly fine in Python 3.x. Please at least try it before complaining.

If you mean "why doesn’t tmp.keys() give me a list any more, that’s not hard to research.

But more importantly, Python 2.7 has not been supported for over 4 years. And the new way has been in place since the beginning of Python 3.x, so over 15 years. And what the new tmp.keys method does, was already done in Python 2 - named tmp.viewkeys. So none of this is new. Not even close.

Well, no, we don’t know that. I could show many, many counterexamples, but that is off topic here.

2 Likes

Indeed, why go to all the complexity of

for i in tmp.keys():

or

for i in list(tmp.keys()):

when you can just do

for i in tmp:

Seems a lot less complicated to me… :slight_smile:

Also, if you want a list of dict keys, why do

tmp.keys()

or

list(tmp.keys())

when you could just do

list(tmp)

Again, seems less complicated than either one, which suggests that Python is not the reason for the complexity here.

And if you’re concerned with performance,

Well, one reason the type of dict.keys(), etc was changed in Python 3 was that it in fact can substantially increase performance, as the iterable is now iterated directly, one item at a time, only as needed, instead of first converting everything to a list and then iterating that.

2 Likes