Python Lists For Your Scripts And Algorithms

One specific tool every programmer uses everyday is what, in Python, we call Lists. And Python lists are relatively simple to use.

A list is a sequence of objects of arbitrary types. In almost every script or algorithm implementation you have to write, chances are you would use a list. Whenever it is needed, you can store objects in a list, and later use that list for doing something in your program.

Here is a quick overview of the features we commonly use, illustrated with code snippets.

How you initialize lists

You can initialize your list to the empty list, using this nice assignment style mylist = list() or the old way mylist = [] depending on what you like.

In the case you wanted to initialize the list to a non-empty value, you would do something specific depending on the case.

If you have to set the members explicitly, you would probably use the [] style, for example:

mylist = [1, 2, 'foo']

If you have to build the list by converting an already defined sequence or container, you could use list(), for example:

mylist = list(an_existing_equence)

Where an_existing_equence would be an object that can be converted to a list, such as a string (which would give the list of characters in the string) or a tuple.

How you add members to a list

To add a member to a list, once it is defined, we use the append() method available for list objects.

A common thing is to iterate over another list (or another iterable object such as a tuple or a dictionary), get some data at each step and append it to the first list. For example:

mylist = [1, 2, 3]

for i in range(2, 10):
    number = 2*i
    mylist.append(number)

An alternate technique is to use the extend() method.

Say you already have a list of new members to add to the first list. As a side note, you could actually build this second list using what we call a list comprehension. It goes like this:

other_numbers = [2*i for i in range(2, 10)]

Then extending the first list with the new one is done using:

mylist = [1, 2, 3]

mylist.extend(other_numbers)

How you check that an object is a member of a list

You use the operator dedicated to list membership checking, the in operator.

Here is an example with an if statement to test the condition and do something if needed:

if x in mylist:
    print(f'Member {x} already in the list')
else:
    # Then, we want to add it
    mylist.append(x)

List comprehensions

We saw an example of a list comprehension previously, but for clarity purpose, let's re-introduce them properly.

One use case where they are very handy is when you need to build new lists of data from attributes or properties you access on objects. For example, given a list of Person objects with firstname and lastname attributes, you would write something like this:

persons = [p1, p2, p3, p4, p5, p6]
firstnames = [p.firstname for p in persons]
lastnames = [p.lastname for p in persons]

Sorting a list

Python makes it very practical to sort a list (and other sequences), using the builtin sorted function.

You will see a full list of examples in the official howto on sorting.

Removing duplicates from a list of strings or numbers

This could be when you discover the set builtin type and one of its practical uses. A set is another Python sequence data structure that do not allow duplicates. So you would just convert the list to a set, The conversion would thus remove the duplicates in the process.

You use the set() callable class (similar to the list() one for lists) for this operation, as in this example:

unique_firstnames = set(firstnames)

Since a set is a sequence, you could use the resulting object for the rest of the program. It is also better performance-wise for operations such as "membership checking".

But if for good reasons you need to come back to a list after the conversion to remove duplicates, you just pass the "set" object to the list() callable.

So the idiom in this case is:

unique_firstnames = list(set(firstnames))

Let's keep learning!

We probably have just seen half of the possibilities and tricks involving Python lists to solve everyday problems.

Interested in using Python and learning more about its features? Content Gardening Studio now has a documentation site where you can find a knowledge base about Python techniques, solutions, and all we focus on here. Use it and send us questions!

comments powered by Disqus

Need help for your project?

Our team can contribute to your project, working on a specific task, or doing all the coding based on your specifications, using Python, a web framework such as Django or a CMS.