1
> [1, 2, 3][1:int(1e9)]
[2, 3]

Coming from C background the above code gives me a mini heart attack. But it seems to work. Is it guaranteed to work in any python3? Is it as efficient as > [1, 2, 3][1:int(2)]? Is it considered bad form as in 'prefer to use anything else before relying on this behavior'?


OK, I've probably described the problem badly. This is my code. The last access is out of bonds most of the time. Is that fine?

def cut(b: bytes, max: int) -> [bytes]:
    '''Chop into pieces no longer than max bytes.'''
    return [b[i:i+max] for i in range(0, len(b), max)]
Vorac
  • 8,726
  • 11
  • 58
  • 101
  • 2
    It's mostly considered "why would you not just use `[1:]`?" As for why it's safe, see https://docs.python.org/3/library/stdtypes.html#common-sequence-operations, note 4. _By definition_ a value greater than `len(s)` is set to `len(s)` as part of resolving the slice. – Mike 'Pomax' Kamermans Jul 04 '23 at 04:18
  • 1
    for your update: yes, that's fine, but you're not guaranteed same sized slices. Whether that's a problem is mostly up to you and what downstream code you've written. – Mike 'Pomax' Kamermans Jul 04 '23 at 04:28
  • 1
    Thanks! Your 2 comments are already an answer so if You would copy-paste them we could resolve the thread. Please also add one sentence on is there a glaringly simpler solution to what I am trying to achieve. – Vorac Jul 04 '23 at 04:30
  • 1
    If you search SO for chunking up a list in python, you'll find a million post that all have "this is fine" as answer, so honestly based on your edit, this is more of a duplicate than anything else. – Mike 'Pomax' Kamermans Jul 04 '23 at 04:32
  • 1
    For example: [How do I split a list into equally-sized chunks?](https://stackoverflow.com/questions/312443/how-do-i-split-a-list-into-equally-sized-chunks) – Mike 'Pomax' Kamermans Jul 04 '23 at 04:32

1 Answers1

1

Yes, it is an intended behavior of Python's slice.

Excerpt from Python's official tutorial:

out of range slice indexes are handled gracefully when used for slicing:

>>> word[4:42]
'on'
>>> word[42:]
''
blhsing
  • 91,368
  • 6
  • 71
  • 106