List and Tuple in Action

Introduction

List and Tuple are often clubbed together and behave quite similar to each other. This article will dive a little deeper in the concepts of list and tuple as compared to our introductory article on data structures in python.

This article is example based where we will encounter several use cases of a list. Let us know in the comments if we have missed out any common use of the list data-structure.

This post is a little lengthier than other posts. Do not fear. We have intensionally done that to provide as many use cases commonly encountered in a day to day activities of a Python Developer.

List from other data structures

Passing any iterable to list() or tuple() constructor returns a list.

list from list [1, 2, 3, 4, 5, 6, 7, 8]
list from tuple [1, 2, 3, 4, 5, 6, 'USA']
list from set [1, 2, 3, 4, 5, 6]
list from dictionary ['two', 'one', 'three']


tuple from list (1, 2, 3, 4, 5, 6, 7, 8)
tuple from tuple (1, 2, 3, 4, 5, 6, 'USA')
tuple from set (1, 2, 3, 4, 5, 6)
tuple from dictionary ('two', 'one', 'three')
      

Passing only dict object into list or tuple constructor creates a list or tuple of dictionary of keys only. We can include dict values as well by passing dict_object.items().

Iterating a list/tuple

1
2
3
4
5
6
1
2
3
4
5
6
      

Iterating with index

Those coming from other programming backgrounds will try to do it something like the below.


The above code is an example of bad code in Python. You don't need to use global len() function to find the length of the list object and then use range to iterate from 0 to length of list - 1. We usually don't do that.The Pythonic way to do the same is shown below.

We use enumerate() function which attaches an index with each item while itearation. Notice that we have two values index and item which are catching the two variables being returned during each iteration.

Checking for emptiness

Many a times, it is required to check if a list is empty or contains some items.

The traditional approach is to find the length of the list using len and then comparing it with 0. In Python, the same approach is not considered a Pythonic way to do things.

Checking for existence of an element

To check whether or not an element exist in a list, in operator can be used.

Note that along with in, not in operator also exists.

Maximum, Minimum, Reverse, Sum And Count in a Python List

Python provides a very similar method to find maximum, minimum, sum and count of elements in any iterable like tuple, set, dicts including a list object.

Apply a function on each element of a list

There are several methods to achive the same. We will present youa few of them.

You can also make a function and then pass the function name as first argument in the map function.

The function above is too short to be given a name. In such cases, we can also use lambda functions as shown below.

Sorting a list

Sorting a list is one of widely used task. Python provides us easy way to sort lists in-place (the affect is on the original object itself) and otherwise, using a sort and sorted function. Both of these functions takes reverse as an argument, which defaults to False and can be provided in case reverse-sort is required.

All these functions internally used Timsort.

See sorting example below using sorted function. Note that you need to catch the result in some variable here because sorted return as new list instead of making changes into original object.

Filtering a list

There are many situations where we want to filter a list, that is, we only require those elements from the list we satisfies a given condition.

Let us see how the same is achieved in Python.

As a little complicated example shown below, we chose only those strings whose length is greater than 3.

Inserting, deleting, extending, poping in list

In the example below, we displayed the following.

  • Adding an element to the end of the list using append
  • Inserting an element at a given index using insert method
  • Extending the list using another list using extend method and + operator
  • An element can be removed by index using pop method
  • An element can also be removed using remove method

Slicing a list

A slice is a method to create view of the original list. It is of great help when we only want a part of the list for our purpose.

A slice can be used in cases like:

  • To use first 10 items of the list
  • Iterate the list reversibly
  • Take last 10 digits of the list
  • Make a view of elements at even positions

A slice takes three parameters (index) as mentioned below

  • start, which defaults to 0
  • stop which defaults to length of the iterable
  • step which defaults to 1

Slice of a list can be created using [start:stop:step] syntax and can be iterated just like a list object. Note that the element at stop is not included.

Below are a few examples of slices.

List Comprehensions

We will talk about list comprehensions in detail in another post but for the sake of completeness, we present you an example for the same here as well.

A list comprehension is a syntactic sugar provided by Python to create a list based on existing iterable. Everything which can be done using list comprehension can be done without them as well but comprehensions makes our code concise, easy to read and fast at the same time.

Other types of comprehensions include dictionary-comprehension and set-comprehension.

Note that we do not have any tuple-comprehension in Python.

Did you see that? A traditional method which takes at least 4 lines of code was brought down to one.

Let us see another example in which we try to find the sum of all the numbers of a 3x3 matrix.

Conclusion

In the article, we talked about lists and some common ways in which it is used and presented a solution to the same. We discussed sorting, list-comprehension, list-slicing, list filtering, finding minimum, maximum, sum and other common operations involving list.

Author image
New Delhi
I am a passionate programmer based in New Delhi, India. I mostly work with Python. Apart from work, I find myself doing poetry and learning about various languages. I prefer chai over coffee.