-5

I have a list my_list = [] In this list are some int's so my_list = [1,2,3,4] Now I want to work with every number one by one, without knowing there are only 4 int's. There could be 1000 things in the list. I thought about sth like:

i = len(self.my_list)
while i > 0:

    print(my_list[i])

    i -=1

but I got this error: IndexError: list index out of range

wallisers
  • 388
  • 3
  • 16

2 Answers2

1

What you could do is iterate over each item in the list:

for i in my_list:
   print(i,i**2)
Comos
  • 82
  • 10
  • Got this Error: TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int' – LittleDuck19 Feb 06 '20 at 15:21
  • 2
    Try to figure out the error yourself. `2` is obviously an integer, so the other value must be the string. The other value is `i`. What it is `i`? `i` is one of the values in the list `my_list`. Conclusion: check the content of your list. I'm sure you'll find at least one string in there. – Matthias Feb 06 '20 at 15:34
0

I usually using this method:

my_list = [1,2,3,4]
i=0
while(i < len(my_list)):
    print(my_list[i])
    i+=1

with while you have control of index.

First Last
  • 19
  • 5
  • 1
    This looks like C or Java code written in Python. Try to think pythonic. A list is iterable, so `for value in my_list:` is the way to go. – Matthias Feb 06 '20 at 15:36
  • as I mentioned with this you have control of your index sometimes i use like this my_list = [1,2,3,4] i=0 while(i < len(my_list)): print(my_list[i]) if(my_list[i] == 2): print(my_list[i-1]) i+=1 – First Last Feb 06 '20 at 15:51
  • 1
    You can be pythonic and have control of index: try `for (i, x) in enumerate(my_list): ...` :) – SPH Feb 06 '20 at 16:54