Python Lists

A list is a collection of objects in a particular order. Lists in Python can consist of the same or different kinds of objects, like numbers, letters or even other lists. You can add, remove and insert elements in any place inside a list.

Create a List

In Python, square brackets ([]) are used to make a list. Each element is separated by a comma.

Empty List

This method will only declare a list, without adding any elements to it.

With elements:

In order to keep your code clean, it’s encouraged to have lines under 120-character long. If the code of your list is too long, you can write it in multiple lines.

Print List

To display a list, use the print function.

This will result in displaying both: an empty list and a list with elements.

[]
['elem1', 'elem2', 'elem3']

Access Elements

You can access any element inside a list, by telling Python the index of a particular item. The index has to be enclosed in square brackets.
Indexing of a list starts from 0. This means, that if you want to display the first element, you have to write the following code.

The result is

ford

Slice Elements

You can slice multiple elements of a list at once by using a range, instead of an index.

Display all elements – list[start:end]

Each line of the code below will display all elements in the list.

If you don’t know the length of a list, use the len function.

or even better don’t enter the second value at all.

Similarly, you can do this with the first value.

But, it gets even easier, because you don’t have to use values at all. Just enter a colon.

Each of these lines of code will result in displaying all the numbers in the list.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Display elements with the step parameter list[start:end:step]

The following code will display every second element in the list.

[0, 2, 4, 6, 8]

Another slice options

The above code will display the last element from a list.

9

This code will slice all the numbers except for the last 3.

[0, 1, 2, 3, 4, 5, 6]

The following code will slice the last three elements from the list.

[7, 8, 9]

Modify Elements

The following list contains three brands of cars

This will change the third element (honda) to ‘mazda’.

['ford', 'bmw', 'mazda']

Add Elements

Let’s suppose, you have a list of three car brands.

In Python, there are three methods you can use to add elements to a list: insert, append and extend.

insert

In this case, python inserts ‘tesla’ in the second position (remember that indexing starts from 0 no 1, so 1 is the second position)

['ford', 'tesla', 'bmw', 'honda']

append

The printed result will be.

['ford', 'bmw', 'honda', ['volvo', 'saab']]

Notice, that even despite the fact that the list new_cars contains two elements, the value is added as a single element.
Use the following code to check the size of a list.

The result is

4

extend

This time, instead of using the append method, we will use extend. This function will add elements as separate values.

Print the result and the number of elements.

As you can see, elements are added separately and the number of elements is 5.

['ford', 'bmw', 'honda', 'volvo', 'saab']
5

Remove elements

You can remove elements from a list by using the remove and pop methods.

This code will remove ‘bmw’ from the list, so it will give us the following result.

['ford', 'honda', ['volvo', 'saab'], 'tesla']

You can also delete sub-lists from the list.

As you can see, the sub list is deleted.

['ford', 'bmw', 'honda', 'tesla']

pop

The pop function always deletes the last value from the list. It takes 0 or 1 argument.

This will give the following result.

['ford', 'bmw', 'honda']

It’s a little bit more complicated when a list gets an argument.
This code will remove the second element from the list.

And give the following result.

['ford', 'honda', ['volvo', 'saab'], 'tesla']

If you want to remove the second element from the end, use the following code.

The result is as follows.

['ford', 'bmw', 'honda', 'tesla']

Remove duplicates

In order to retrieve the unique elements from a list, you need to use a set. Sets are unordered collections of unique objects.
The following list has a few non-unique elements.

If you print a result you will get the following ordered list of unique items.

[0, 1, 2, 4, 5, 6, 8, 9]

Copy a List

The simplest method to create a copy of a list is to use the list function.

If you use the following code cars_copy = cars, python won’t create a copy of a list, but an alias to that list. Now, if you modify one list, the second one will also change.

This code will remove the last element.

['ford', 'bmw']

Sum a List

You can sum elements in a list by using the sum function. Remember that all elements in a list have to be numbers. If you try to insert text or another list, it will result in an error.

This code will return

15.8

Sort a List

I will present to you two ways you can use to sort a list.

Sort temporary

This code will assign the sorted elements from the list numbers to a new list, called sorted_numbers.

Now, when you execute the code the value of numbers won’t change.

[1, 2.1, 3, 4.7, 5]
[2.1, 1, 5, 3, 4.7]

Sort permanently

This function returns None, so you can’t use it to assign a list to another list. Instead, use this code.

This returns the sorted list of numbers, but this time the numbers list stays ordered.

[1, 2.1, 3, 4.7, 5]

Empty a List

In order to empty a list, you can use a few different ways. I’ll show you two of them. The following list contains a number of elements. Both methods use the slice assignment (:).

The first way you can empty a list is by using the following code.

You can achieve the same result with the del keyword.

When you execute the code, it will return the same result, which is [].
In order to check if a List is empty, use the following code.

Shuffle a List

You can shuffle elements inside a list with the shuffle function.
First, you will have to import this function from the random module. Next, use the function to shuffle the elements.

The result is a randomly shuffled list of elements.

[0, 9, 7, 1, 6, 2, 5, 4, 8, 3]

Iterate through a List

In Python, you can loop through a list using the for loop. If you used other programming languages, like C# or Java you know that the for loop in Python is different than in other languages. It works similarly to foreach in C#.

The result is.

ford
bmw
honda
volvo
saab
tesla

If you want to have both the items and indexes, you can use the enumerate function:

When you execute the code, that’s what you will get.

0 ford
1 bmw
2 honda
3 volvo
4 saab
5 tesla

Reverse a List

I will show you two ways you can use to create a reversed list.
The first function, called reverse will overwrite the original list – numbers.

The output will be as follows:

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

The second method will display reversed results, but will not change the list itself.

And the result is.

9 8 7 6 5 4 3 2 1 0

List operations

In Python, you can use arithmetic operators, such as + and * with lists. These operators work similarly to those used with strings. Take a look.
The following code will add to the list.

The result is the same as with the extend function.

Result.

[1, 2, 3, 4, 5]

List and Strings

This part of the lesson talks about operations you can perform when working with strings and lists.

Split string to list

The following code will convert a string to a list. For this exercise, we will use the split method.

This will give us the following result.

['one', 'two', 'three', 'four', 'five', 'six']

By default, the delimiter in the split function is a space ( ). You can change that by adding a parameter. Take a look at the next example.

This time words are separated by a dash (-). The split(‘-‘) method will recognize it and will split the string accordingly.

Convert a list to a string

Alternatively, you can merge list elements with the join function.

The result is:

bmw, opel, ford

List size

There are two ways to check the size of a list.

The first way is to use the len function.

The second way is to use the __len__ function.