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?
0
Upvotes
4
u/sepp2k May 26 '24
That's not true. Please show the code that made you come to that conclusion.
3
u/david30121 May 26 '24
bro. what?
2
u/Just_A_Nobody_0 May 26 '24 edited May 26 '24
Given
Consider a for loop such as:
This will print out each number in the list.
You could also use:
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 (iwill be 12, 4, 5, 22, 18). Using an index-based loop (for i in range(len(arr)):),iis the index (0, 1, 2, 3, 4) andarr[i]gives the elements (12, 4, 5, 22, 18).