Skip to Content
Functional Python Programming - Second Edition
book

Functional Python Programming - Second Edition

by Steven F. Lott
April 2018
Intermediate to advanced content levelIntermediate to advanced
408 pages
10h 42m
English
Packt Publishing
Content preview from Functional Python Programming - Second Edition

Picking subsets with islice()

In Chapter 4, Working with Collections, we looked at slice notation to select subsets from a collection. Our example was to pair up items sliced from a list object. The following is a simple list:

flat= ['2', '3', '5', '7', '11', '13', '17', '19',  '23', '29', '31', '37', '41', '43', '47', '53',  '59', '61', '67', '71',...  ]

We can create pairs using list slices as follows:

>>> list(zip(flat[0::2], flat[1::2]))[(2, 3), (5, 7), (11, 13), ...]

The islice() function gives us similar capabilities without the overhead of materializing a list object. This will work with an iterable of any size. It looks like the following:

flat_iter_1= iter(flat)
flat_iter_2= iter(flat)
zip(    islice(flat_iter_1, 0, None, 2),  islice(flat_iter_2, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Python Programming - Third Edition

Functional Python Programming - Third Edition

Steven F. Lott

Publisher Resources

ISBN: 9781788627061Supplemental Content