#๐Ÿ”’ How to obtain the first element on a list with reverse slice?

30 messages ยท Page 1 of 1 (latest)

hoary bronze
#

How to obtain the first element in a list when I am using the (reversed) slice object.

I want to return 10 from the list when using [::-1] slice type object.

x = [10, 20, 30, 40] 
x[1:0:-1] # returns 20
x[1:-1:-1] # Does not return 10
x[0::-1] # Note: I can't use it since I am decrementing a variable here
lofty geodeBOT
#

@hoary bronze

Python help channel opened

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.

devout ingot
#

maybe you mean x[-1], which selects the last element from the list

cursive cedar
#

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

hoary bronze
devout ingot
#

why?

austere tangle
#

[::-1][-1]

cursive cedar
#

what are you actually trying to do here?

hoary bronze
cursive cedar
#

what is the loop for?

austere tangle
#

Maybe just share your code

steel sundial
#

probably overcomplicating it

austere tangle
#

That's what I'm thinking

cursive cedar
#

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

hoary bronze
devout ingot
#

is there any reason you need it to be done with a -1 slice? why can't you just print(x[i])?

hoary bronze
#

There is.

austere tangle
#

Hmm. From the code you shared there really isn't though

#

Can you share your actual code?

austere tangle
devout ingot
#

and -- why can't you use x[0::-1]? that gives you what you want

hoary bronze
devout ingot
#

but it doesn't have to be, no?

hoary bronze
#

Thanks for trying. I'll close it now.

#

!close

lofty geodeBOT
#
Python help channel closed

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.