#๐ How to obtain the first element on a list with reverse slice?
30 messages ยท Page 1 of 1 (latest)
@hoary bronze
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
maybe you mean x[-1], which selects the last element from the list
i assume you mean that you want to slice out a list with a single element containing the first element
you'll need to elaborate on what you mean by I can't use it since I am decrementing a variable here
I need to retain the slice format
why?
[::-1][-1]
what are you actually trying to do here?
It is in a loop where I am changing the 2nd variable in the slice object.
what is the loop for?
Maybe just share your code
probably overcomplicating it
That's what I'm thinking
it's possible that you will just have to make it a special case in the end
the way indices jump from 0 to -1 in python is a common special case
I've suspected that, and trying to confirm it.
@austere tangle Code won't add more to my question.
x = [10, 20, 30, 40]
for i in range(len(x)):
print(x[i:i-1:-1])
# OUTPUT
#[] # Missing
#[20]
#[30]
#[40]
The question is if slice operator can do fetch the missing item.
is there any reason you need it to be done with a -1 slice? why can't you just print(x[i])?
There is.
Hmm. From the code you shared there really isn't though
Can you share your actual code?
There's still my original answer too
what is that reason?
and -- why can't you use x[0::-1]? that gives you what you want
because the code is in a x[variable:variable:-1] format.
but it doesn't have to be, no?
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.