Python language basics 47: 2 ways to reverse the elements in a list

Introduction

In the previous post we looked at 2 ways to sort the elements in a list. The sort function operated directly on the list and the sorted function accepted another list as an argument and returned a new list. You could use the sorted function in case you need an independent sorted list and leave the source intact.

In this post we’ll look at two ways to reverse the elements in a list.

Reversing

Reversing the elements in a list also comes in 2 distinct forms. One that operates directly on the source, i.e. reverses the items within it, and another one which creates an independent object with the reversed items. However, we’ll see shortly that the usage of that function is not that straightforward.

Consider the following list of cities:

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

The direct reversing function is simply called ‘reverse’:

cities.reverse()

‘cities’ will be…

[‘Zürich’, ‘Birmingham’, ‘Paris’, ‘Berlin’, ‘Budapest’, ‘Stockholm’]

If you don’t want to modify the original list but create a reversed copy then you can use the ‘reversed’ function. However, it doesn’t return the reversed list but an object of type iterable. We’ll look at iterables later on in this course. For now it’s enough to know that the returned iterable can be passed into the list constructor in order to have a reference to the reversed list:

rev_iterable = reversed(cities)
cities_reversed = list(rev_iterable)

‘cities_reversed’ will become…

[‘Zürich’, ‘Birmingham’, ‘Paris’, ‘Berlin’, ‘Budapest’, ‘Stockholm’]

..whereas the original ‘cities’ list will be the same as before.

In the next post we’ll look at the enumerate function for tuples.

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: