slice or islice? When to use which - Deepstash

Explore the World's Best Ideas

Join today and uncover 100+ curated journeys from 50+ topics. Unlock access to our mobile app with extensive features.

slice

slice

slice(stop)

slice(start, stop, [step])

  • Standard indexing relies on slice()a[start:stop:step] calls a.__getitem__(slice(start, stop, step)).
  • slice() creates a shallow copy of the selected elements from the original list.
  • Whenever you slice a list, the Python interpreter creates a new list and populates it with references to the elements you selected from the original list. Given that a reference needs 8 bytes on 64-bit systems, the overhead of copying references becomes noticeable when working with large lists. For example, slicing 1000 elements allocates almost 8kb worth of references.

2

11 reads

itertools.islice

islice(iterable, stop)

islice(iterable, start, stop, [step])

  • Returns an iterator that produces the selected elements from the iterable. It skips start elements from the iterable, and then produces values until stop is reached, or until the iterator is exhausted. This affects execution speed when it needs to skip lots of elements.
  • It's memory efficient because it doesn't allocate extra memory for the iterated elements, and it can be used to slice both iterables and iterators. Standard indexing (a[start:stop]) doesn't work on iterators because they don't implement __getitem__().

2

7 reads

slice or islice?

Choosing between slice() and islice() is a trade-off between memory usage and iteration speed. slice() is faster, but requires more memory, whereas islice() allocates a constant amount of memory, but is slower.

Use slice() when:

  • you need fast iteration speed, and you afford the extra memory usage

Use islice() when:

  • you need to slice iterators, or
  • memory efficiency is important to you

2

8 reads

CURATED BY

ocpodariu

Alt account of @ocp. I use it to stash ideas about software engineering

CURATOR'S NOTE

🐍 Python docs & Stack Overflow

Read & Learn

20x Faster

without
deepstash

with
deepstash

with

deepstash

Access to 200,000+ ideas

Access to the mobile app

Unlimited idea saving & library

Unlimited history

Unlimited listening to ideas

Downloading & offline access

Personalized recommendations

Supercharge your mind with one idea per day

Enter your email and spend 1 minute every day to learn something new.

Email

I agree to receive email updates