Python language basics 44: slicing a list

Introduction

In the previous post we looked at the index function for collections. We saw how it helped find the location of an object by returning the position as an integer.

In this post we’ll look at how to slice a list.

Slicing

You probably know the English word ‘slice’, e.g. a slice of bread. Slicing a collection is similar. In the case of a collection slicing means extracting a subset of the collection into another one.

Consider the following collection of cities:

cities = ["Stockholm", "Budapest", "Berlin", "Paris", "Birmingham", "Zürich"]

Say you’d like to extract all elements from position 1 – i.e. the second element “Budapest” – to and including the position 4, i.e. “Birmingham”. Slicing is an indexer-based operation, i.e. there’s no “slice” method or similar. The start index is inclusive and the end index is exclusive which is called a half-open range. The indexes are separated by a colon ‘:’.

Hence the solution looks as follows:

reduced = cities[1:5]

‘reduced’ will look as follows:

[‘Budapest’, ‘Berlin’, ‘Paris’, ‘Birmingham’]

It’s OK to ignore either the start or the end index. The following will extract all elements starting from position 3:

reduced = cities[3:]

[‘Paris’, ‘Birmingham’, ‘Zürich’]

Whereas the following code extract everything from the start up until position 3:

reduced = cities[:3]

[‘Stockholm’, ‘Budapest’, ‘Berlin’]

Slicing can be used to to copy a list which we’ll look at in the next post among other techniques for creating copies.

Read all Python-related posts on this blog here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: