A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_itertools_islice_function.htm below:

Python itertools.islice() Function

Python itertools.islice() Function

The Python itertools.islice() function is used to return selected elements from an iterable. Unlike regular slicing, it works with iterators and does not require materializing the entire sequence in memory.

This function is useful when working with large datasets or infinite iterators. By specifying a start, stop, and step, we can extract a portion of an iterable efficiently.

Syntax

Following is the syntax of the Python itertools.islice() function −

itertools.islice(iterable, start, stop[, step])
Parameters

This function accepts the following parameters −

Return Value

This function returns an iterator that yields elements based on the given slicing parameters.

Example 1

Following is an example of the Python itertools.islice() function. Here, we extract the first five elements from a range −

import itertools

numbers = range(10)
selected = itertools.islice(numbers, 5)
for num in selected:
   print(num)

Following is the output of the above code −

0
1
2
3
4
Example 2

Here, we extract a portion of a list starting from index 2 and stopping at index 6 using the itertools.islice() function −

import itertools

letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
selected = itertools.islice(letters, 2, 6)
for letter in selected:
   print(letter)

Output of the above code is as follows −

c
d
e
f
Example 3

Now, we use itertools.islice() function with a step parameter to skip elements −

import itertools

numbers = range(20)
selected = itertools.islice(numbers, 2, 15, 3)
for num in selected:
   print(num)

The result obtained is as shown below −

2
5
8
11
14
Example 4

We can use itertools.islice() function with an infinite iterator to control its output. Here, we use it with itertools.count() function to limit the output −

import itertools

counter = itertools.count(10, 2)
selected = itertools.islice(counter, 5)
for num in selected:
   print(num)

The result produced is as follows −

10
12
14
16
18

python_modules.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4