-1

I recently learnt that the expression "in range(len(li)" is considered un-pythonic. So I read posts explaining that enumerate should be used instead. My question is how I could convert my current for loop (used for bubblesort) to enumerate correctly. My original loop looks like:

 a = [4,2,5,7,3,99,-2,8767,27,1]
 for j in range(len(a) - 1):

What I tried so far was:

for j, _ in enumerate(a) -1:

However this gave me the error: TypeError: unsupported operand type(s) for -: 'list' and 'int'

I noticed that this error has to do with the -1 since this is the only loop in my code that causes this problem.

Hiach
  • 1

1 Answers1

1

It might help to see it this way:

If you only want each item:

>>> for item in a:
...     print(item)
... 
4
2
5
7
3
99
-2
8767
27
1

If you want an index as well:

>>> for index, item in enumerate(a):
...     print(index, item)
... 
0 4
1 2
2 5
3 7
4 3
5 99
6 -2
7 8767
8 27
9 1