my_array=[1,2,3]
my_array1=['John','Tom','Peter']
search=int(input("Enter your number"))
for i in range(0,3):
if search==my_array[i]: ### can you please point out the purpose of this '[i]' ? what does it do?
print(my_array1[i]) ### also this one
-
See the tutorials on lists here: https://docs.python.org/3/tutorial/introduction.html#lists – Mark Mar 12 '20 at 14:35
-
`my_array[i]` is accessing an element of `my_array` by position. for example, `my_array[0]` returns the first element of the list (counting starts at 0, not 1 here). – Dan Mar 12 '20 at 14:35
-
@G.Anderson This post doesn't use slices, does it? – John Gordon Mar 12 '20 at 14:40
-
Still valid as an extension of indexing notation IMO – G. Anderson Mar 12 '20 at 14:42
-
I'm voting to close this, it's a trivial question which is unlikely to benefit future readers. – AMC Mar 12 '20 at 19:32
1 Answers
my_array1
is a list. This list holds three elements, 'John'
as the first element, 'Tom'
as the second element and 'Peter'
as the third element. In this case, the elements are strings, but list can hold any type of elements, like for example my_array
which contains integers. When you want to do stuff with an element in a list, you need a way to access this element. You access an element in a list with the square brackets []
and the position of the element in the list. It is important to note, that the numbering of element starts at 0. So the first element, 'John'
is at position 0 in the list. To access it, you write my_array1[0]
. Similarly, to access the second and third element, you write my_array1[1]
and my_array1[2]
.
Now to answer your question: i
is nothing more than a substitution for any number, in your program for the numbers 0, 1 or 2. So if i
is 1, writing my_array1[i]
is the same as writing my_array1[1]
and accesses the second element in my_array1
, which is 'Tom'
.

- 198
- 1
- 11
-
Thank you very much. I understood about accessing an element in a list but I was not clear why 'i' was in there but I get it now. Thank you. – Leo Zarni Mar 12 '20 at 15:05