Working with Python lists


In programming and in Python you often find yourself in the need for different data structures to solve problems by means of algorithms, one of the most common data structures are lists, in Python a list is a data structure to hold sequences of data or information, it is already built-in in Python and since everything in Python is an object, the list data type comes with batteries included, some really helpful methods that we can take advantage of. This entry is the first of a set of two entries about Python lists.

logo

Let's start by defining some lists.

first_list = []
second_list = list()

These are the different alternatives you can use to define a list in Python. You can use square brackets [] to initialize an empty string, or you can use the verbose built-in method list.

You can use the first one to initialize your list with some elements.

first_list = [1, 2, 3, 4]

In this case we are using integers, but we have to remember also that Python is a dynamically typed language, despite other compiled languages where sequences are the same type, in Python you can save any data type in one list.

different_types = [1, "hello", 24.5, False]

This is excellent but what else can we do?

Indexing and Slicing

Indexing lists

We access any element inside a list to get or set a value, we can do this indexing the list using square brackets also [].

>>> different_types = [1, "hello", 24.5, False]
>>> print(different_types[0])
1
>>> print(different_types[3])
False

Something to point out is that in Python, indexes start in zero (0), and goes all the way to the size of the list minus one. You can also use reverse indexing.

>>> different_types = [1, "hello", 24.5, False]
>>> print(different_types[-1]) # last element
False
>>> print(different_types[-2]) # previous to the last element
24.5

You access the elements by providing the negative offset from the last element. You can set the value of an element in the sequence as well.

>>> different_types = [1, "hello", 24.5, False]
>>> different_types[1] = (2, 4)
>>> print(different_types)
[1, (2, 4), 24.5, False]

If you try to use an index greater than the size minus one, you will get an IndexError raised in the execution.

>>> different_types = [1, "hello", 24.5, False]
>>> different_types[5]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    different_types[5]
IndexError: list index out of range

Slicing lists

With slicing, you can create smaller versions of a list, the way we can do this is also using square brackets [], but with the main difference is that we have to provide two indexes, the start index and the stop index (this is not included in the output), let's see some examples

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[0:4]
[1, 2, 3, 4]

You can also use negative indexes to slice your lists.

>>> numbers[-4:-2]
[5, 6]

You can also ignore of these indexes, if you do not provide the start index the default behavior is the following.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[:4]
[1, 2, 3, 4]

You will the elements from the beginning to the stop index. If you do not provide the stop index the default behavior is the following.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[4:]
[5, 6, 7, 8]

You will get the elements from the start index up to the end of the list. If you do not provide any of the indexes you will get a new copy of the list.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[:]
[1, 2, 3, 4, 5, 6, 7, 8]

Reversing a list

A really cool trick in Python to reverse the elements in a list is to use the following.

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8]
>>> numbers[::-1]
[8, 7, 6, 5, 4, 3, 2, 1]

Mutability

Python lists are mutable, what does this mean? there two basic characteristics to understand about mutable types, the first is that their value can be changed after definition, the other one is that mutable types can be passed by reference as default behavior. let's do some code to show this better.

>>> a = [1, 2, 3, 4, 5]
>>> b = a

Let's create a list and another one, this last is assigned the first list. In this assignment b is going to be an identifier referencing the same list a. If we change something in b we are in fact change that something in a.

>>> b[3] = 20
>>> print(a)
[1, 2, 3, 20, 5]

This feature can be helpful in some situations but a problem in others, mainly when we pass a list to a function. If we want to break this default behavior we can create a new copy of the list by slicing from the beginning to the end.

>>> a = [1, 2, 3, 4, 5]
>>> b = a[:]
>>> b[3] = 20
>>> print(b)
[1, 2, 3, 20, 5]
>>> print(a)
[1, 2, 3, 4, 5]

Built-in Methods

We can use the power of the built-in Python methods in combination with lists to obtain relevant data.

Maximum of a list

We can get the maximum element in a list using the max built-in method.

>>> a = [1, 2, 3, 4, 5]
>>> max(a)
5

Minimum of a list

As well, we can get the minimum element in a list using the min built-in method.

>>> a = [1, 2, 3, 4, 5]
>>> min(a)
1

Something to consider is that in order make an appropriate use of these built-in with lists is to use the same data types among the elements of the list, or in the case in which we have different data types, there must be valid > or < operations among the types, one example is a list of integers and floats.

>>> a = [1, 2.3, 3, 4.88, 5]
>>> min(a)
1

Size of a list

We can also determine the amount of elements in a list using the len built-in method.

>>> a = [1, 2, 3, 4, 5]
>>> len(a)
5

Sorting a list

We can sort the elements of a list by using the sort method, this will return a new list with the same elements but sorted.

>>> a = [2, 1, 4, 5, 3]
>>> sorted(a)
[1, 2, 3, 4, 5]

Reverse sorting

We can perform a reverse sorting by using an extra argument to the sorted method called reverse, we have to supply True to obtained a reverse sorted list.

>>> a = [2, 1, 4, 5, 3]
>>> sorted(a, reverse=True)
[1, 2, 3, 4, 5]

The same way as min and max, in order to sort the elements in a list, there must be valid > or < operations among the types.

Conclusion

This short but concise post has been the introduction to the most common used tools in Python in to handle lists, in a further post we will talk about more tools and cool features to use with lists like list comprehension.

0 Comments

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel