0

I was trying to loop over a list in python using the indices but it drops error. Can you guys help me out with this? What could be the syntax that could fix this ?

abs = [10,20,40] 

for i in abs: 
    new_abs = abs[i]+ abs[i+1]
    print(new_abs)

So, i have managed to use hard code for the temporary use.

abs = [10,20,40] 
new_abs = [ abs[0], abs[0]+ abs[1] , abs[1]+abs[2] ] 
print(new_abs)

Can you please, let me know the proper syntax to loop over this index numbers?

Patrick Artner
  • 43,256
  • 8
  • 36
  • 57
  • What are you trying to do? – shivank98 Apr 26 '20 at 10:35
  • How to i run new_abs in a loop? – hemanth sharma Apr 26 '20 at 10:37
  • `i` should be the indices, you're currently looping on the values. Use `for i in range(len(abs)-1):` – Thierry Lathuille Apr 26 '20 at 10:38
  • didn't get you. may be you would like to define what `new_abs` is ? `for i in range(len(abs)): print(abs[i])` syntax iterate through list with the help of indexes. and `for i in abs: print(i)` will directly print your elements in abs. – shivank98 Apr 26 '20 at 10:39
  • `print(abs[0])` followed by `for index, item in enumerate(abs[:-1]): print(item+abs[index+1])` would be the solution to your summation problem - `enumerate(abs[:-1])` to avoid IndexError for the last element - at least thats the logic of your second code parts – Patrick Artner Apr 26 '20 at 10:45

1 Answers1

0

Looping over lists in python you have few options

for i in abs:
   print(i)

will print you all items in the lists. If you want to loop over lists items with indexes you can use

for index, item in enumerate(abs):
    print(index, item)

that will lop over each item and will provide you the index number of the item in the list and the current item.

Leo Arad
  • 4,312
  • 2
  • 4
  • 16