Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I want to use itertools.islice instead of normal list slicing?

It seems to me that many functions in the itertools module have easier equivalents. For example, as far as I can tell, itertools.islice(range(10),2,5) does the same thing as range(10)[2:5], and itertools.chain([1,2,3],[4,5,6]) does the same thing as [1,2,3]+[4,5,6]. The main documentation page mentions speed advantages, but are there any reasons to choose itertools besides this?

like image 910
Luke Taylor Avatar asked Aug 23 '15 23:08

Luke Taylor


People also ask

What does Itertools Islice do?

islice() In Python, Itertools is the inbuilt module that allows us to handle the iterators in an efficient way. They make iterating through the iterables like lists and strings very easily.

What is the use of Islice?

islice() - The islice() function allows the user to loop through an iterable with a start and stop , and returns a generator. map() - The map() function creates an iterable map object that applies a specified transformation to every element in a chosen iterable.

Why do we use Itertools?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

What does Itertools Islice return?

Itertools islice method returns an iterator which returns the individual values on iterating or traversing over.


1 Answers

To address the two examples you brought up:

import itertools   data1 = range(10)  # This creates a NEW list data1[2:5]  # This creates an iterator that iterates over the EXISTING list itertools.islice(data1, 2, 5)   data2 = [1, 2, 3] data3 = [4, 5, 6]  # This creates a NEW list data2 + data3  # This creates an iterator that iterates over the EXISTING lists itertools.chain(data2, data3) 

There are many reasons why you'd want to use iterators instead of the other methods. If the lists are very large, it could be a problem to create a new list containing a large sub-list, or especially create a list that has a copy of two other lists. Using islice() or chain() allows you to iterate over the list(s) in the way you want, without having to use more memory or computation to create the new lists. Also, as unutbu mentioned, you can't use bracket slicing or addition with iterators.

I hope that's enough of an answer; there are plenty of other answers and other resources explaining why iterators are awesome, so I don't want to repeat all of that information here.

like image 116
Cyphase Avatar answered Sep 24 '22 19:09

Cyphase