slice last 4 items from a list

B

brad

Is this the correct way to slice the last 4 items from a list?

x = [1,2,3,4,5,6,7,8,9]
print x[-4:]

It works, but is it Pythonic?
 
B

Bruno Desthuilliers

brad a écrit :
Is this the correct way to slice the last 4 items from a list?

x = [1,2,3,4,5,6,7,8,9]
print x[-4:]

It works, but is it Pythonic?

Is there a more obvious (for a pythonic definition of 'obvious') way to
do it ? If no, then it's pythonic... Now FWIW, I usually use
'esrever'[::-1] to reverse a string, so I may not be a reference !-)
 
J

John Machin

Is this the correct way to slice the last 4 items from a list?

x = [1,2,3,4,5,6,7,8,9]
print x[-4:]

It works, but is it Pythonic?

It's Pythonic. It's also unambiguous, unlike your specification, which
could be interpreted as 'chop off the last 4 items from a list' i.e.
del x[-4:]. What you are actually doing is 'print the last 4 items of
a list'.
 
L

Lawrence D'Oliveiro

Is this the correct way to slice the last 4 items from a list?

x = [1,2,3,4,5,6,7,8,9]
print x[-4:]

It works, but is it Pythonic?

It's Pythonic. It's also unambiguous, unlike your specification, which
could be interpreted as 'chop off the last 4 items from a list' ...

No, the OP is using "slice" in the technically correct CS sense.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,792
Messages
2,569,639
Members
45,353
Latest member
RogerDoger

Latest Threads

Top