+ 2

Python question

How do I know if I should use positive or negative indexing?

2nd Mar 2025, 1:34 PM
Joe Potter
Joe Potter - avatar
7 Réponses
+ 8
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.
2nd Mar 2025, 2:13 PM
Wong Hei Ming
Wong Hei Ming - avatar
+ 10
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']
2nd Mar 2025, 4:40 PM
Lothar
Lothar - avatar
+ 8
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.
2nd Mar 2025, 2:30 PM
Bob_Li
Bob_Li - avatar
+ 4
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.
4th Mar 2025, 9:15 AM
HAMZA NABULSI
+ 2
When you don't know how long your string is
3rd Mar 2025, 12:44 PM
Daniel
Daniel - avatar
+ 1
Hi
3rd Mar 2025, 7:31 PM
Ahmed Didy
Ahmed Didy - avatar
0
Use positive indexing (list[0]) to access elements from the start and negative indexing (list[-1]) to access elements from the end. Negative indexing is useful when working with the last few elements without knowing the exact length.
5th Mar 2025, 2:47 AM
Muhammad Abdul Wasea
Muhammad Abdul Wasea - avatar