"
This article is part of in the series
Last Updated: Wednesday 29th December 2021

The Python lists are widely used in python. Lists are one of the most used data structures in Python. It's an unordered data store. In this article, we will learn how to work with lists in Python. You should know Python syntax and what is the lists in python. We have talked in a previous article, about the python dictionary data structure.

The lists are a sequential data store. Item saved in the list by its index. The list index starts with 0. This mean that a simple list  x = [1, 2, 3]. To get the 1st item you will need the item by index. This might be confusing. Don't worry we will explain. Let's start with

Create a List in Python

To define lists in Python there are two ways. The first is to add your items between two square brackets.

Example:

items = [1, 2, 3, 4]

The 2nd method is to call the Python list built-in function by passing the items to it.

Example:

Items  = list(1, 2,3,4)

In both cases, the output will be

[1, 2, 3, 4]

The list can accept any data type. You can have a list of integers and strings. List in python doesn't enforce to have a single item type in it. You can have a list of different items.

[1, 'name', {"key" : "value"}, list(1, 2, 3)]

This gives you the flexibility to add multiple data types in the list. You can add a list inside this list. This is called a nested list. Now we store our data into a python list it's time to know how to do more with these data.

Append Items to the List in Python

The list is a mutable data structure. This means you can create a list and edit it. You can add, insert, delete items to the created list. To add items to the list you can use the function and passing the value you want to add. The append function will add the item at the end of the list. The function lets you insert data in the place you want on the list. It'll take two parameters, the index, and the value. Let's see an example:

items = ["mobile", "laptop", "headset"]

# append the keyboard item to the list 
items.append("keyboard")
print(items)

# output
['mobile', 'laptop', 'headset', 'keyboard']


# insert the mouse item to the list in before the laptop item
items.insert(1, "mouse")
print(items)

# output
['mobile', 'mouse', 'laptop', 'headset', 'keyboard']

Sort Lists in Python

We mentioned above that the Python list is unordered. The list is stored in memory like this. You can see a detailed implementation of the Python list here.

mrzxv

This means that to access the value in item inside the list you have to call it by its index. More simply if we have student's name list `students = ["John", "Jack", "Christine"]` and you want to get the name of the 1st student. You will need to know the index of this student's name. In our case, it's the zero index. The syntax will be student[0]

Let's see a real-world example to understands it clearly.

Students = ["John", "Jack", "Christine"]
for i in Students:
    print(Students [i])

# Output
John
Jack
Christine

The list has unordered items. To sort them you can make use of the built-in python function sorted(). It'll go through the list items and sort them.

The usage of the sorted() function is very simple. You need to pass the list to the sorted function. It'll return the sorted list and change the original list too.

Example:

x = [4, 5, 1, 8, 2]
print(sorted(x))

# output
[1, 2, 4, 5, 8]

The first question that will come to your mind is how it works? it can sort the integers. What about the other types of the data string, dictionaries..etc. The sort function is more dynamic in sorting. This means that you can pass the sorting mechanism you want the list to be sorted based on. The first argument we can pass it to the sort function is reverse.

Note:  The difference between sorted() and sort() The sort()  change the orginal list. The sorted() doesn't change the orginal list. It'll retun the new soted list.

Reverse Lists in Python

The sort function can reverse the list order. Set the reverse key to True will make Python automatically reverse the list sort. Let's see an example.

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars)) 

# output
['a', 'b', 'o', 'y', 'z'] 

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars, reverse=True)) 

# output
['z', 'y', 'o', 'b', 'a']

This example shows you how to reverse a list. In this example, we reverse the alphabetical order of the list.

Advanced Sorting

You can add a customized sorting for the list by passing the sorting function in the key parameter.

chars = ["z", "y", "o", "b", "a"]
print(sorted(chars))

# output
['a', 'b', 'o', 'y', 'z']

words = ["aaaa", "a", "tttt", "aa"]
print(sorted(words, key=len))

# output
['a', 'aa', 'aaaa', 'tttt']


engineers = [
    {'name': 'Alan Turing', 'age': 25, 'salary': 10000},
    {'name': 'Sharon Lin', 'age': 30, 'salary': 8000},
    {'name': 'John Hopkins', 'age': 18, 'salary': 1000},
    {'name': 'Mikhail Tal', 'age': 40, 'salary': 15000},
]

# using custom function for sorting different types of data.
def get_engineer_age(engineers):
    return engineers.get('age')

engineers.sort(key=get_engineer_age)
print(engineers)

# output
[
    {'name': 'John Hopkins', 'age': 18, 'salary': 1000},
    {'name': 'Alan Turing', 'age': 25, 'salary': 10000},
    {'name': 'Sharon Lin', 'age': 30, 'salary': 8000},
    {'name': 'Mikhail Tal', 'age': 40, 'salary': 15000}
]

In the above examples, we used the key option to pass a sorting method to the sort function. The default one we used in chars array is sorting based on the order. In this list, the order was alphabetical. In the words list, we have a list of different words length. We want to sort it by the length of the word. The key we passed to the sort function is the built-in len() function. This will tell Python to sort the list based on the word length.

In the engineer's example. This more likely to be an issue you need to solve in a more real-world example. You have a list of engineers data and you want to sort them based on the customized method. In our example, we sorted it by age.

Conclusion

Python List is a very powerful data structure. Mastering it will get you out of a lot of daily issues in Python. You can create a list with single or multiple data types. You can append the list and insert data in the index you want. The most used function in the list is the sorted method. You can sort the list based on the different criteria you want. You can know more about List form the Python official documentation.