When executing this code:

greeting = ['Здравствуйте', 'вам надо решить как можно больше правильных примеров', 'Ответ вписывайте после двоиточия'] i = 0 for i in greeting: print (greeting[i]) i += 1 

an error occurs:

TypeError: list indices must be integers, not str

  • Because you change the number i to a string in the loop for i - andreymal

3 answers 3

Because your program does not reach the addition step i += 1 , since your variable i assigned to the value of the array and becomes type str i.e. greeting['Здравствуйте'] , after which the expression i + 1 is executed and an error is issued that the value of i is of type str and cannot be folded:

 greeting = ['Здравствуйте', 'вам надо решить как можно больше правильных примеров', 'Ответ вписывайте после двоиточия'] # i = 0 for i in greeting: print(i) print(type(i)) 

Conclusion

 Здравствуйте <class 'str'> вам надо решить как можно больше правильных примеров <class 'str'> Ответ вписывайте после двоиточия <class 'str'> 

In order for your program to work correctly, you should do:

 greeting = ['Здравствуйте', 'вам надо решить как можно больше правильных примеров', 'Ответ вписывайте после двоиточия'] x = 0 for y in greeting: print(greeting[x]) x += 1 

or

 greeting = ['Здравствуйте', 'вам надо решить как можно больше правильных примеров', 'Ответ вписывайте после двоиточия'] for y in greeting: print(y) 

Conclusion

 Здравствуйте вам надо решить как можно больше правильных примеров Ответ вписывайте после двоиточия 
  • 2
    the code doesn't reach i+=1 here. TypeError on the greeting[i] expression is thrown. The phrase “i is assigned to an array” is not clear. The name i refers to the current list item at each iteration. - jfs
  • @jfs thanks edited by - Twiss

In the for i in greeting: loop for i in greeting: at each iteration, i not an index, but refers to the element itself in the greeting list. Therefore, i is a string, not an integer.

For example, on the first iteration, greeting[i] equivalent to greeting['Здравствуйте'] and calls TypeError .

To print a greeting on separate lines:

 for s in greeting: print(s) 

Or (briefly and works also for non-string elements):

 print(*greeting, sep='\n') 

What does * (asterisk) and ** double asterisk mean in Python?

     greeting = ['Здравствуйте', 'вам надо решить как можно больше правильных примеров', 'Ответ вписывайте после двоиточия'] i = 0 for x in greeting: print(greeting[i]) i += 1