Why does Python start at index -1 (as opposed to 0) when indexing a list from the end? [duplicate]Understanding slice notationAngular ContentChildren of extended classFinding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?What is the difference between Python's list methods append and extend?Why is it string.join(list) instead of list.join(string)?Accessing the index in 'for' loops?How to remove an element from a list by index?How to make a flat list out of list of listsHow do I get the number of elements in a list?How to clone or copy a list?How do I list all files of a directory?
Did Joe Biden "stop a prosecution" into his son in Ukraine? And did he brag about stopping the prosecution?
Found a minor bug, affecting 1% of users. What should QA do?
How do French and other Romance language speakers cope with the movable do system?
Question about modelling birdcage
What is the difference and relation between chanda and cetana?
Duck, duck, gone!
NMinimize is wrong : why?
The answer is a girl's name (my future granddaughter) - can anyone help?
Why not add cuspidal curves in the moduli space of stable curves?
Looking for circuit board material that can be dissolved
Rover vs pathfinder vs lander?
Could the Queen overturn the UK Supreme Court ruling regarding prorogation of Parliament?
Could Boris Johnson face criminal charges for illegally proroguing Parliament?
How is this situation not a checkmate?
Why does the Pilatus PC-24 have such a large "Wing Support"?
Disable all sound permanently
What is the Japanese equivalent of 'you're in my heart'?
How to identify whether a publisher is genuine or not?
What is the difference between increasing volume and increasing gain?
What powers or limits devil promotion?
Should I be an author on another PhD student's paper if I went to their meetings and gave advice?
Booting Ubuntu from USB drive on MSI motherboard -- EVERYTHING fails
Sending mail to the Professor for PhD, after seeing his tweet
Realistically, how much do you need to start investing?
Why does Python start at index -1 (as opposed to 0) when indexing a list from the end? [duplicate]
Understanding slice notationAngular ContentChildren of extended classFinding the index of an item given a list containing it in PythonWhat does the “yield” keyword do?What is the difference between Python's list methods append and extend?Why is it string.join(list) instead of list.join(string)?Accessing the index in 'for' loops?How to remove an element from a list by index?How to make a flat list out of list of listsHow do I get the number of elements in a list?How to clone or copy a list?How do I list all files of a directory?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;
This question already has an answer here:
Understanding slice notation
32 answers
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
marked as duplicate by wim, cs95
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 16 at 17:56
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
|
show 1 more comment
This question already has an answer here:
Understanding slice notation
32 answers
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
marked as duplicate by wim, cs95
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 16 at 17:56
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
64
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
Apr 15 at 16:22
10
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
7
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
6
Should that sayas opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.
– Raimund Krämer
Apr 16 at 9:30
2
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30
|
show 1 more comment
This question already has an answer here:
Understanding slice notation
32 answers
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
python list
This question already has an answer here:
Understanding slice notation
32 answers
list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"
print(list[-4]) # Number -4 is "a"
This question already has an answer here:
Understanding slice notation
32 answers
python list
python list
edited Apr 16 at 7:03
glglgl
71.4k8 gold badges106 silver badges174 bronze badges
71.4k8 gold badges106 silver badges174 bronze badges
asked Apr 15 at 8:12
abrahamabraham
4251 gold badge2 silver badges6 bronze badges
4251 gold badge2 silver badges6 bronze badges
marked as duplicate by wim, cs95
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 16 at 17:56
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by wim, cs95
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 16 at 17:56
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by wim, cs95
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Apr 16 at 17:56
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
64
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
Apr 15 at 16:22
10
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
7
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
6
Should that sayas opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.
– Raimund Krämer
Apr 16 at 9:30
2
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30
|
show 1 more comment
64
Don't uselist
as a variable name, it's the name of a standard class.
– Barmar
Apr 15 at 16:22
10
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
7
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
6
Should that sayas opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.
– Raimund Krämer
Apr 16 at 9:30
2
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30
64
64
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
Apr 15 at 16:22
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
Apr 15 at 16:22
10
10
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
7
7
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
6
6
Should that say
as opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.– Raimund Krämer
Apr 16 at 9:30
Should that say
as opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.– Raimund Krämer
Apr 16 at 9:30
2
2
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30
|
show 1 more 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":
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~
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.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
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
I have summarized python tricks like this, in case you are interested.
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', son<2
is used here. just 5 line solve a complex problem. @Konrad
– recnac
Apr 16 at 12:38
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
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
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
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
Apr 15 at 16:56
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
Apr 15 at 22:54
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
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
You can also think it as shorthand for
list[len(list) - x]
where x is the element position from the back.
This is valid only if0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
10
I think-0
is0
pretty much everywhere.
– Koray Tugay
Apr 15 at 15:43
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not0
anymore. @Barmar
– Koray Tugay
Apr 15 at 16:37
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
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 indices larger than -1 + len(xs)
or smaller than -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
|
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 can't step to the left from the first element, so the first step to the left wraps around to the last element.
add a comment
|
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
Suppose you start from a
to d
, a is your staring point where you stand (or your home), so mark it as 0(because you did not move yet),
Move one step to b, second step to c and arrive at third d.
Then how about you return from d to a (or return from your office to your home). Your home is 0
because your family live there, so your office cannot be a 0
.It's your last stop.
So when you return back to home. d is the last first stop to where you start off for home, c is the last second ....
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?
– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer
– Algebra
Apr 16 at 10:02
add a comment
|
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":
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~
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.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
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
I have summarized python tricks like this, in case you are interested.
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', son<2
is used here. just 5 line solve a complex problem. @Konrad
– recnac
Apr 16 at 12:38
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
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":
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~
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.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
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
I have summarized python tricks like this, in case you are interested.
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', son<2
is used here. just 5 line solve a complex problem. @Konrad
– recnac
Apr 16 at 12:38
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
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":
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~
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.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
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
I have summarized python tricks like this, in case you are interested.
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":
"""swap mirror node"""
def reverse(arr: List[int]) -> None:
for i in range(len(arr) // 2):
arr[i], arr[~i] = arr[~i], arr[i]
"""find median in a sort list"""
def median(arr: List[float]) -> float:
mid = len(arr) // 2
return (arr[mid] + arr[~mid]) / 2
"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))
~
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.
# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
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
I have summarized python tricks like this, in case you are interested.
edited Apr 28 at 2:32
answered Apr 15 at 8:16
recnacrecnac
3,1976 gold badges9 silver badges38 bronze badges
3,1976 gold badges9 silver badges38 bronze badges
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', son<2
is used here. just 5 line solve a complex problem. @Konrad
– recnac
Apr 16 at 12:38
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
add a comment
|
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', son<2
is used here. just 5 line solve a complex problem. @Konrad
– recnac
Apr 16 at 12:38
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Apr 16 at 0:27
1
1
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.
– Konrad
Apr 16 at 12:01
2
2
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', so
n<2
is used here. just 5 line solve a complex problem. @Konrad– recnac
Apr 16 at 12:38
Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', so
n<2
is used here. just 5 line solve a complex problem. @Konrad– recnac
Apr 16 at 12:38
1
1
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.
– Paddy3118
Apr 16 at 16:22
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
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
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
Apr 15 at 16:56
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
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
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
Apr 15 at 16:56
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 Apr 15 at 8:14
rdasrdas
7,6223 gold badges14 silver badges28 bronze badges
7,6223 gold badges14 silver badges28 bronze badges
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
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
Apr 15 at 16:56
add a comment
|
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
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
Apr 15 at 16:56
11
11
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
In my opinion this answer is better than the accepted one.
– NicolasB
Apr 15 at 12:17
9
9
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
Apr 15 at 16:56
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
Apr 15 at 16:56
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
Apr 15 at 22:54
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
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
Apr 15 at 22:54
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
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 Apr 16 at 2:27
answered Apr 15 at 18:15
T. SarT. Sar
3712 silver badges11 bronze badges
3712 silver badges11 bronze badges
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
Apr 15 at 22:54
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
add a comment
|
"Think about a[2] and a[-2]" isa
the list, or an element of the list?
– detly
Apr 15 at 22:54
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
"Think about a[2] and a[-2]" is
a
the list, or an element of the list?– detly
Apr 15 at 22:54
"Think about a[2] and a[-2]" is
a
the list, or an element of the list?– detly
Apr 15 at 22:54
1
1
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
"a" is an hypothetical list which contains the values a-h! I'll clarify!
– T. Sar
Apr 16 at 2:27
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
Note the similarity with modular arithmetic.
– Code-Apprentice
Apr 16 at 17:54
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
You can also think it as shorthand for
list[len(list) - x]
where x is the element position from the back.
This is valid only if0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
10
I think-0
is0
pretty much everywhere.
– Koray Tugay
Apr 15 at 15:43
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not0
anymore. @Barmar
– Koray Tugay
Apr 15 at 16:37
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
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
You can also think it as shorthand for
list[len(list) - x]
where x is the element position from the back.
This is valid only if0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
10
I think-0
is0
pretty much everywhere.
– Koray Tugay
Apr 15 at 15:43
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not0
anymore. @Barmar
– Koray Tugay
Apr 15 at 16:37
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
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
You can also think it as shorthand for
list[len(list) - x]
where x is the element position from the back.
This is valid only if0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
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
You can also think it as shorthand for
list[len(list) - x]
where x is the element position from the back.
This is valid only if0 < -(-x) < len(list)
print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a
edited Apr 18 at 11:31
answered Apr 15 at 8:15
AshishAshish
2,0886 silver badges30 bronze badges
2,0886 silver badges30 bronze badges
10
I think-0
is0
pretty much everywhere.
– Koray Tugay
Apr 15 at 15:43
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not0
anymore. @Barmar
– Koray Tugay
Apr 15 at 16:37
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
add a comment
|
10
I think-0
is0
pretty much everywhere.
– Koray Tugay
Apr 15 at 15:43
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not0
anymore. @Barmar
– Koray Tugay
Apr 15 at 16:37
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
10
10
I think
-0
is 0
pretty much everywhere.– Koray Tugay
Apr 15 at 15:43
I think
-0
is 0
pretty much everywhere.– Koray Tugay
Apr 15 at 15:43
9
9
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
@KorayTugay Except in floating point.
– Barmar
Apr 15 at 16:24
I guess that is not
0
anymore. @Barmar– Koray Tugay
Apr 15 at 16:37
I guess that is not
0
anymore. @Barmar– Koray Tugay
Apr 15 at 16:37
7
7
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.
– curiousdannii
Apr 15 at 23:41
3
3
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.
– Martin Bonner
Apr 16 at 8:07
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 indices larger than -1 + len(xs)
or smaller than -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 indices larger than -1 + len(xs)
or smaller than -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 indices larger than -1 + len(xs)
or smaller than -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 indices larger than -1 + len(xs)
or smaller than -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.
edited Apr 23 at 21:13
answered Apr 16 at 0:32
Gregory NisbetGregory Nisbet
3,4622 gold badges15 silver badges36 bronze badges
3,4622 gold badges15 silver badges36 bronze badges
add a comment
|
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 can't step to the left from the first element, so the first step to the left wraps around to the last element.
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 can't step to the left from the first element, so the first step to the left wraps around to the last element.
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 can't step to the left from the first element, so the first step to the left wraps around to the last element.
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 can't step to the left from the first element, so the first step to the left wraps around to the last element.
edited Apr 24 at 12:46
answered Apr 15 at 13:39
OscarOscar
814 bronze badges
814 bronze badges
add a comment
|
add a comment
|
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
Suppose you start from a
to d
, a is your staring point where you stand (or your home), so mark it as 0(because you did not move yet),
Move one step to b, second step to c and arrive at third d.
Then how about you return from d to a (or return from your office to your home). Your home is 0
because your family live there, so your office cannot be a 0
.It's your last stop.
So when you return back to home. d is the last first stop to where you start off for home, c is the last second ....
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?
– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer
– Algebra
Apr 16 at 10:02
add a comment
|
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
Suppose you start from a
to d
, a is your staring point where you stand (or your home), so mark it as 0(because you did not move yet),
Move one step to b, second step to c and arrive at third d.
Then how about you return from d to a (or return from your office to your home). Your home is 0
because your family live there, so your office cannot be a 0
.It's your last stop.
So when you return back to home. d is the last first stop to where you start off for home, c is the last second ....
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?
– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer
– Algebra
Apr 16 at 10:02
add a comment
|
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
Suppose you start from a
to d
, a is your staring point where you stand (or your home), so mark it as 0(because you did not move yet),
Move one step to b, second step to c and arrive at third d.
Then how about you return from d to a (or return from your office to your home). Your home is 0
because your family live there, so your office cannot be a 0
.It's your last stop.
So when you return back to home. d is the last first stop to where you start off for home, c is the last second ....
You could intuitively understand it this way
steps= ["a", "b", "c", "d"]
Suppose you start from a
to d
, a is your staring point where you stand (or your home), so mark it as 0(because you did not move yet),
Move one step to b, second step to c and arrive at third d.
Then how about you return from d to a (or return from your office to your home). Your home is 0
because your family live there, so your office cannot be a 0
.It's your last stop.
So when you return back to home. d is the last first stop to where you start off for home, c is the last second ....
edited Apr 23 at 11:02
answered Apr 16 at 8:54
AlgebraAlgebra
5,9382 gold badges27 silver badges51 bronze badges
5,9382 gold badges27 silver badges51 bronze badges
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?
– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer
– Algebra
Apr 16 at 10:02
add a comment
|
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?
– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer
– Algebra
Apr 16 at 10:02
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?– Raimund Krämer
Apr 16 at 9:35
d is the last first stop to start, c is the last second
This is kind of difficult to understand, could you dissect that sentence a bit?– Raimund Krämer
Apr 16 at 9:35
last
here is ending or final, not recent @RaimundKrämer– Algebra
Apr 16 at 10:02
last
here is ending or final, not recent @RaimundKrämer– Algebra
Apr 16 at 10:02
add a comment
|
64
Don't use
list
as a variable name, it's the name of a standard class.– Barmar
Apr 15 at 16:22
10
It isn't starting at 1, it's starting at -1. ?!?
– Thomas Weller
Apr 15 at 20:21
7
mod arithmetic should really be mentioned on this page somewhere...
– Nacht
Apr 16 at 0:14
6
Should that say
as opposed to -0
? Since it starts at 0 when indexing from the start, it is trivial that it can't be 0 from the end, so I think -0 is what is meant.– Raimund Krämer
Apr 16 at 9:30
2
Did you try accessing index 0?
– jpmc26
Apr 16 at 14:30