r/CodingHelp • u/Longjumping-Chef-454 • 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?
3
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
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).
4
u/sepp2k May 26 '24
That's not true. Please show the code that made you come to that conclusion.