Python Forum
Preferred way to slice a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Preferred way to slice a list
#2
Don't worry about the one true way to do things. That is probably the most often broken part of the Zen of Python.

I don't think either [4:] or [-4:] is more Pythonic. Here's how I would think of it. The colon is to the right, so it's printing everything to the right of that index. The first one prints everything after the fourth item, and the second one prints the last four items (because of the negative). If your intent is to get 'the last four digits', then I think [-4:] is clearer. More important than that is what if you get a 9 item list? or a 7 item list. In either of those cases, [-4:] will give you the correct number of items, but [4:] may not give you the right number of items.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: Preferred way to slice a list - by ichabod801 - Dec-09-2019, 10:12 PM
RE: Preferred way to slice a list - by perfringo - Dec-09-2019, 10:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Fix pandas copy/slice warning. deanhystad 3 907 Sep-07-2023, 03:18 PM
Last Post: deanhystad
  Slice creates new objects? fmr300 4 1,373 Jul-20-2022, 12:34 PM
Last Post: fmr300
  InvalidIndexError: (slice(None, None, None), slice(None, -1, None)) SuperNinja3I3 1 4,578 Jul-15-2022, 05:59 AM
Last Post: Larz60+
  Slice list Moris526 1 1,680 Dec-24-2020, 02:19 AM
Last Post: deanhystad
  increase and decrease a slice value? KEYS 2 2,150 Nov-10-2020, 11:35 PM
Last Post: KEYS
  Pass Tuple as a Slice nagymusic 2 2,405 Dec-12-2019, 04:42 AM
Last Post: nagymusic
  slice python array on condition Gigux 2 2,312 Nov-03-2019, 07:21 PM
Last Post: Larz60+
  How to append and drop to next line while slice/indexing emryscass 3 2,667 Sep-26-2019, 01:06 PM
Last Post: Malt
  Is Event.set() the preferred way to stop a thread? svetlanarosemond 5 3,904 Jul-17-2018, 08:14 AM
Last Post: DeaD_EyE
  Understanding slice copying in for loop yksingh1097 5 4,131 Jul-02-2018, 01:03 PM
Last Post: yksingh1097

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020