Why does Python start at index -1 when indexing a list from the end? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?Finding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?Difference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?Accessing the index in 'for' loops?How do I remove an element from a list by index in Python?Getting the last element of a list in PythonHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?Does Python have a string 'contains' substring method?
Is a manifold-with-boundary with given interior and non-empty boundary essentially unique?
Is there a Spanish version of "dot your i's and cross your t's" that includes the letter 'ñ'?
Sorting numerically
What are the motives behind Cersei's orders given to Bronn?
What is the correct way to use the pinch test for dehydration?
Does accepting a pardon have any bearing on trying that person for the same crime in a sovereign jurisdiction?
3 doors, three guards, one stone
What are the pros and cons of Aerospike nosecones?
List *all* the tuples!
Did Xerox really develop the first LAN?
What makes black pepper strong or mild?
Letter Boxed validator
Withdrew £2800, but only £2000 shows as withdrawn on online banking; what are my obligations?
How do I stop a creek from eroding my steep embankment?
ListPlot join points by nearest neighbor rather than order
Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?
I am not a queen, who am I?
Doubts about chords
When is phishing education going too far?
Is there a concise way to say "all of the X, one of each"?
If Jon Snow became King of the Seven Kingdoms what would his regnal number be?
Is the Standard Deduction better than Itemized when both are the same amount?
If 'B is more likely given A', then 'A is more likely given B'
How can I make names more distinctive without making them longer?
Why does Python start at index -1 when indexing a list from the end?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?Finding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?Difference between append vs. extend list methods in PythonDoes Python have a ternary conditional operator?Accessing the index in 'for' loops?How do I remove an element from a list by index in Python?Getting the last element of a list in PythonHow do I get the number of elements in a list in Python?How do I concatenate two lists in Python?Does Python have a string 'contains' substring method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
New contributor
add a comment |
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
New contributor
28
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
11 hours ago
8
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
1
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago
add a comment |
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
New contributor
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
python list
New contributor
New contributor
edited 1 hour ago
Aaron Hall♦
185k53310264
185k53310264
New contributor
asked 19 hours ago
abrahamabraham
22126
22126
New contributor
New contributor
28
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
11 hours ago
8
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
1
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago
add a comment |
28
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
11 hours ago
8
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
1
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago
28
28
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
11 hours ago
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
11 hours ago
8
8
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
1
1
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago
add a comment |
7 Answers
7
active
oldest
votes
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
def reverse(arr):
for i in range(len(arr)//2):
arr[i], arr[~i] = arr[~i], arr[i]
def median(arr):
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
Discussion about whether should use python tricks like ~
:
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
add a comment |
list[-1]
Is short hand for:
list[len(list)-1]
The len(list)
part is implicit. That's why the -1
is the last element. That goes for any negative index - the subtraction from len(list)
is always implicit
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
add a comment |
Because -0
in Python is 0
.
With 0
you get first element of list and
with -1
you get the last element of the list.
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # "d"
I think-0
is0
pretty much everywhere.
– Koray Tugay
11 hours ago
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not0
anymore. @Barmar
– Koray Tugay
10 hours ago
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
add a comment |
This is the mnemonic method I use. It is just an approach of what is happening, but it works.
Don't think of those as indexes. Think of them as offsets on a circular list.
Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:
You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).
If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
add a comment |
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.
New contributor
add a comment |
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than len(xs)
or smaller than -1-len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
add a comment |
In a comment, abraham asked
I wish python has another mechanism to get list backward.
For another way to access lists backwards, one could simply first reverse the list and then access the elements as usual:
lst = ["a", "b", "c", "d"]
print(lst[::-1][0]) # "d"
print(lst[::-1][1]) # "c"
New contributor
2
True, but not really answer the question "why".
– Valentino
16 hours ago
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
abraham is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55684960%2fwhy-does-python-start-at-index-1-when-indexing-a-list-from-the-end%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
7 Answers
7
active
oldest
votes
7 Answers
7
active
oldest
votes
active
oldest
votes
active
oldest
votes
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
def reverse(arr):
for i in range(len(arr)//2):
arr[i], arr[~i] = arr[~i], arr[i]
def median(arr):
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
Discussion about whether should use python tricks like ~
:
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
add a comment |
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
def reverse(arr):
for i in range(len(arr)//2):
arr[i], arr[~i] = arr[~i], arr[i]
def median(arr):
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
Discussion about whether should use python tricks like ~
:
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
add a comment |
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
def reverse(arr):
for i in range(len(arr)//2):
arr[i], arr[~i] = arr[~i], arr[i]
def median(arr):
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
Discussion about whether should use python tricks like ~
:
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
To explain it in another way, because -0
is equal to 0
, if backward starts from 0
, it is ambiguous to the interpreter.
If you are confused about -
, and looking for another way to index backwards more understandably, you can try ~
, it is a mirror of forward:
arr = ["a", "b", "c", "d"]
print(arr[~0]) # d
print(arr[~1]) # c
The typical usages for ~
are like "swap mirror node" or "find median in a sort list":
def reverse(arr):
for i in range(len(arr)//2):
arr[i], arr[~i] = arr[~i], arr[i]
def median(arr):
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
~
actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.
Discussion about whether should use python tricks like ~
:
In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.
For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.
def findStrobogrammatic(self, n):
nums = n % 2 * list('018') or ['']
while n > 1:
n -= 2
# n < 2 is so genius here
nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
return nums
edited 9 hours ago
answered 19 hours ago
recnacrecnac
1,9202524
1,9202524
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
add a comment |
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
2 hours ago
add a comment |
list[-1]
Is short hand for:
list[len(list)-1]
The len(list)
part is implicit. That's why the -1
is the last element. That goes for any negative index - the subtraction from len(list)
is always implicit
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
add a comment |
list[-1]
Is short hand for:
list[len(list)-1]
The len(list)
part is implicit. That's why the -1
is the last element. That goes for any negative index - the subtraction from len(list)
is always implicit
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
add a comment |
list[-1]
Is short hand for:
list[len(list)-1]
The len(list)
part is implicit. That's why the -1
is the last element. That goes for any negative index - the subtraction from len(list)
is always implicit
list[-1]
Is short hand for:
list[len(list)-1]
The len(list)
part is implicit. That's why the -1
is the last element. That goes for any negative index - the subtraction from len(list)
is always implicit
answered 19 hours ago
DroidX86DroidX86
2,281919
2,281919
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
add a comment |
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
5
5
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
In my opinion this answer is better than the accepted one.
– NicolasB
15 hours ago
3
3
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.
– plugwash
10 hours ago
add a comment |
Because -0
in Python is 0
.
With 0
you get first element of list and
with -1
you get the last element of the list.
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # "d"
I think-0
is0
pretty much everywhere.
– Koray Tugay
11 hours ago
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not0
anymore. @Barmar
– Koray Tugay
10 hours ago
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
add a comment |
Because -0
in Python is 0
.
With 0
you get first element of list and
with -1
you get the last element of the list.
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # "d"
I think-0
is0
pretty much everywhere.
– Koray Tugay
11 hours ago
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not0
anymore. @Barmar
– Koray Tugay
10 hours ago
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
add a comment |
Because -0
in Python is 0
.
With 0
you get first element of list and
with -1
you get the last element of the list.
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # "d"
Because -0
in Python is 0
.
With 0
you get first element of list and
with -1
you get the last element of the list.
list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # "d"
edited 19 hours ago
answered 19 hours ago
AshishAshish
1,457630
1,457630
I think-0
is0
pretty much everywhere.
– Koray Tugay
11 hours ago
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not0
anymore. @Barmar
– Koray Tugay
10 hours ago
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
add a comment |
I think-0
is0
pretty much everywhere.
– Koray Tugay
11 hours ago
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not0
anymore. @Barmar
– Koray Tugay
10 hours ago
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
I think
-0
is 0
pretty much everywhere.– Koray Tugay
11 hours ago
I think
-0
is 0
pretty much everywhere.– Koray Tugay
11 hours ago
2
2
@KorayTugay Except in floating point.
– Barmar
10 hours ago
@KorayTugay Except in floating point.
– Barmar
10 hours ago
I guess that is not
0
anymore. @Barmar– Koray Tugay
10 hours ago
I guess that is not
0
anymore. @Barmar– Koray Tugay
10 hours ago
1
1
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
3 hours ago
add a comment |
This is the mnemonic method I use. It is just an approach of what is happening, but it works.
Don't think of those as indexes. Think of them as offsets on a circular list.
Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:
You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).
If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
add a comment |
This is the mnemonic method I use. It is just an approach of what is happening, but it works.
Don't think of those as indexes. Think of them as offsets on a circular list.
Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:
You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).
If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
add a comment |
This is the mnemonic method I use. It is just an approach of what is happening, but it works.
Don't think of those as indexes. Think of them as offsets on a circular list.
Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:
You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).
If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)
This is the mnemonic method I use. It is just an approach of what is happening, but it works.
Don't think of those as indexes. Think of them as offsets on a circular list.
Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:
You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).
If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)
edited 55 mins ago
answered 9 hours ago
T. SarT. Sar
181110
181110
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
add a comment |
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
"Think about a[2] and a[-2]" is
a
the list, or an element of the list?– detly
4 hours ago
"Think about a[2] and a[-2]" is
a
the list, or an element of the list?– detly
4 hours ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
55 mins ago
add a comment |
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.
New contributor
add a comment |
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.
New contributor
add a comment |
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.
New contributor
Another explanation:
Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.
Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.
New contributor
New contributor
answered 13 hours ago
OscarOscar
213
213
New contributor
New contributor
add a comment |
add a comment |
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than len(xs)
or smaller than -1-len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
add a comment |
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than len(xs)
or smaller than -1-len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
add a comment |
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than len(xs)
or smaller than -1-len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than len(xs)
or smaller than -1-len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.
answered 2 hours ago
Gregory NisbetGregory Nisbet
3,24321334
3,24321334
add a comment |
add a comment |
In a comment, abraham asked
I wish python has another mechanism to get list backward.
For another way to access lists backwards, one could simply first reverse the list and then access the elements as usual:
lst = ["a", "b", "c", "d"]
print(lst[::-1][0]) # "d"
print(lst[::-1][1]) # "c"
New contributor
2
True, but not really answer the question "why".
– Valentino
16 hours ago
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
add a comment |
In a comment, abraham asked
I wish python has another mechanism to get list backward.
For another way to access lists backwards, one could simply first reverse the list and then access the elements as usual:
lst = ["a", "b", "c", "d"]
print(lst[::-1][0]) # "d"
print(lst[::-1][1]) # "c"
New contributor
2
True, but not really answer the question "why".
– Valentino
16 hours ago
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
add a comment |
In a comment, abraham asked
I wish python has another mechanism to get list backward.
For another way to access lists backwards, one could simply first reverse the list and then access the elements as usual:
lst = ["a", "b", "c", "d"]
print(lst[::-1][0]) # "d"
print(lst[::-1][1]) # "c"
New contributor
In a comment, abraham asked
I wish python has another mechanism to get list backward.
For another way to access lists backwards, one could simply first reverse the list and then access the elements as usual:
lst = ["a", "b", "c", "d"]
print(lst[::-1][0]) # "d"
print(lst[::-1][1]) # "c"
New contributor
edited 14 hours ago
New contributor
answered 16 hours ago
Michael EngenMichael Engen
12
12
New contributor
New contributor
2
True, but not really answer the question "why".
– Valentino
16 hours ago
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
add a comment |
2
True, but not really answer the question "why".
– Valentino
16 hours ago
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
2
2
True, but not really answer the question "why".
– Valentino
16 hours ago
True, but not really answer the question "why".
– Valentino
16 hours ago
4
4
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
It's a waste of ressources to create a whole new list in order to retrieve a single element.
– Eric Duminil
15 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
What is the use of showing another way to solve a task when it is all of, syntaxly, logically and computationally more complex than the standard method?
– Sam
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
@Sam Why use C when we got Assembly?
– mid
11 hours ago
add a comment |
abraham is a new contributor. Be nice, and check out our Code of Conduct.
abraham is a new contributor. Be nice, and check out our Code of Conduct.
abraham is a new contributor. Be nice, and check out our Code of Conduct.
abraham is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55684960%2fwhy-does-python-start-at-index-1-when-indexing-a-list-from-the-end%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
28
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
11 hours ago
8
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
7 hours ago
1
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
3 hours ago