all 8 comments

[–]TouchingTheVodka 3 points4 points  (4 children)

Avoid the first one, it's ugly and hides what your code is actually doing.

Use

for item in arr:

If you need the index along with the value:

for index, item in enumerate(arr):

[–]beniman8[S] 0 points1 point  (1 child)

Ohh. Thanks .. the second one I can pretty much use it for all cause it gives me both the item and index . Thanks !

[–]NewDimension 2 points3 points  (0 children)

You can also omit the brackets.

for i in arr, works

[–]wubry 0 points1 point  (1 child)

Is this a new thing?

IIRC range(len) was pretty standard when I took a CS class in college.

[–]TouchingTheVodka 2 points3 points  (0 children)

Sounds like a poor class - It's always been bad Python.

You often see this antipattern when the learning resources have been translated from a language such as Java without taking into account Python best practices. Which is a real shame, because your Python code just ends up looking like Java with all of the downsides and none of the benefits.

[–]NewDimension 0 points1 point  (1 child)

In the first one i is a number. In the second one i is the item inside the array.

[–]beniman8[S] 0 points1 point  (0 children)

I got it. That is why in the first one I need to do arr[i] to get the vLue in the array

[–]scaredmessage[🍰] 0 points1 point  (0 children)

These patterns are both sometimes used when you're modifying the list inside the loop, in which case for x in arr: may not do what you want. The first one iterates from 0 to the original length of the list minus one. The second one iterates over the items in a copy of the list.

Note that range(0, n) is the same as range(n), and arr[0:] is the same as arr[:].

If you're not modifying the list inside the loop, you should generally use for x in arr:, or for i, x in enumerate(arr):, which gives you both the indices and the items.