Lists
Explore the fundamentals of Python lists including their creation with different data types, combining lists, sorting techniques, and slicing. Understand in-place sorting behavior to manage list data effectively in your programming projects.
We'll cover the following...
Creating a list
A Python list is similar to an array in other languages. In Python, an empty list can be created in the following ways.
my_list = []
my_list = list()
As you can see, you can create the list using square brackets or by using the Python built-in, list. A list contains a list of elements, such as strings, integers, objects or a mixture of types. Let’s take a look at some examples:
my_list = [1, 2, 3]
my_list2 = ["a", "b", "c"]
my_list3 = ["a", 1, "Python", 5]
The first list has 3 integers, the second has 3 strings and the third has a mixture. You can also create lists of lists like this:
Combining two lists
Occasionally, you’ll want to combine two lists together. The first way is to use the extend method:
A slightly easier way is to just add two lists together (yes, it really is that easy).
Sort a list
You can also sort a list. Let’s spend a moment to see how to do that:
Now there is a got-cha above. Can you see it? Let’s do one more example to make it obvious:
In this example, we try to assign the sorted list to a variable. However, when you call the sort() method on a list, it sorts the list in-place. So if you try to assign the result to another variable, then you’ll find out that you’ll get a None object, which is like a Null in other languages. Thus when you want to sort something, just remember that you sort them in-place and you cannot assign it to a different variable.
Slice a list
You can slice a list just like you do with a string:
This code returns a list of just the first 3 elements.