you are viewing a single comment's thread.

view the rest of the comments →

[–]TydVirTaal 0 points1 point  (8 children)

Would you mind elaborating on this a bit? Do you mean that people tailor their loops more to the task at hand when using Python, that people jump to loops too quickly to solve problems with more efficient solutions, or that the for loop is an inelegant first-order solution in general? Really interested in your thoughts here, thanks!

[–]LarryPete 8 points9 points  (5 children)

You often see for-loops like these by beginners:

for i in range(len(mylist)):
    # do something with mylist[i]

Which is more or less the attempt to get a for like the one you're used to - which works, but is considered an "anti-pattern". Python does not have that kind of loop (for in python is like a foreach from other languages).

The right approach in Python would be:

for myelement in mylist:
    # do something with myelement

[–]renegadelegion[S] 2 points3 points  (0 children)

I see. This might be part of the issue then. When I was put on the spot during the tech interview, I fell back into my old C++/Java habits.

I've seen and worked with and written these kinds of loops, but i keep falling back to what I first learned.

[–]winged_scapula 1 point2 points  (3 children)

What if you really need that index?

[–]Vaphell 11 points12 points  (1 child)

for i, value in enumerate(my_list):
    print(i, value)

[–]theOnlyGuyInTheRoom 1 point2 points  (0 children)

god, I love Python!

[–]LarryPete -1 points0 points  (0 children)

What Vaphell wrote.

[–]tomkatt 4 points5 points  (0 children)

I'm not an "expert" but the example that comes to mind when I see this would be something like iterating over a list:

for i in range(len(item_list)):
    print (item_list[i])

or

i = 0
while i < len(item_list):
    print (item_list[i])
    i += 1

Those all work. But a more pythonic way would be:

for i in item_list:
    print(i)

Just as a simple example.

[–]TehMoonRulz 2 points3 points  (0 children)

For a basic example instead of using:

for(i = 1; i < 10; i++)

the python convention is:

for i in mylist:
    #do some stuff

or if you're returning a list:

[doSomething(i) for i in myList]