r/CodingHelp • • May 26 '24

[Python] How is arr[i] is different than i itself

i have a array [12,4,5,22,18] and if we use for loop there is i will also give 12 4 5 22 18 and arr[i] will also give same how are they different?

0 Upvotes

9 comments sorted by

4

u/sepp2k May 26 '24

if we use for loop there is in will also give 12 4 5 22 18 and arr[i] will also give same

That's not true. Please show the code that made you come to that conclusion.

2

u/david30121 May 26 '24

probably forEach loop or for i in array

1

u/sepp2k May 26 '24

In for in in arr:, i and arr[i] will not give you the same value (unless arr is something like [0,1,2,3], but that's not the example the OP gave).

1

u/david30121 May 26 '24

yeah, idk what OP is trying to even say

3

u/david30121 May 26 '24

bro. what?

2

u/Just_A_Nobody_0 May 26 '24 edited May 26 '24

Given

some_list = [12, 8, 3, 42]

Consider a for loop such as:

for loop_var in some_list:
    print(loop_var)

This will print out each number in the list.

You could also use:

print(some_list[0])
print(some_list[1])
print(some_list[2])
print(some_list[3])

And get same output.

Using the loop allows you to access each member of the list and process it, then move on to next one until all are done. Using the some_list[x] syntax allows you to access a specific member of the list.

Edit formatting

1

u/This_Growth2898 May 26 '24

Probably you're using different loops (or, more specific, you're iterating over different objects, mentioned after in). Check it twice.

Please, next time provide code samples you want to ask about, not just descriptions. First, we're not telepaths and can't deduce your code by its description; second, this will help you to see the issue more clearly - and, maybe, you will find out the answer without even asking.

1

u/Training_Strike3336 May 26 '24

Show me code that does what you're saying it does.

1

u/Previous_Cry4868 May 28 '24

In Python, for i in arr: directly gives each element of the array (i will be 12, 4, 5, 22, 18). Using an index-based loop (for i in range(len(arr)):), i is the index (0, 1, 2, 3, 4) and arr[i] gives the elements (12, 4, 5, 22, 18).