-4
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 
Mark
  • 90,562
  • 7
  • 108
  • 148
Leo Zarni
  • 13
  • 1
  • 3

1 Answers1

0

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'.

sfun
  • 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