+ 1
Python question
How do I know if I should use positive or negative indexing?
3 Respuestas
+ 9
Joe Potter ,
Bob_Li has mentioned to use *negative indexing* if we wanted to get something that is close to the end of the elements.
here is a code that demonstrates this with a sample for negative indexing
> task: read the last three characters of each element in the list, regardless of its length, and store them in a new list.
# version using a loop
data = ['1007a03', '12c04', '37005b09']
new_data = []
for temp in data:
new_data.append(temp[-3:])
print(new_data)
> result: ['a03', 'c04', 'b09']
+ 7
The choice is yours.
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr[9] is the same as arr[-1] which is 10.
Normally you would want to use negative index to retrieve elements from the back.
Unless you are doing the lesson, then you should follow the instruction or how the code is written.
+ 7
use negative indexing if what you want is near the end of the list.
generally, you only really use arr[-1].
this is easier than writing arr[len(arr)-1] to access the last element since you don't have to care how long your list is.
Most of the time, though, positive indexing is what you will use.