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 a List

To display a list, use the print function.

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

 

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

 

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 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.

 

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

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

 

Another slice options

The above code will display the last element from a list.
This code will slice all the numbers except the last 3.
The following code will slice the last three elements from the list.
 

Modify Elements

The following list contains a three brands of cars

This will change the third element (honda) to ‘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)
 

append

The printed result will be.
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
 

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.

 

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.

You can also delete sub lists from the list.

As you can see, the sub list is deleted.

 

pop

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

This will give the following result.

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.

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

The result is as follows.

 

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.

 

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.

 

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

 

Sort a List

I will present 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.

 

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.

 

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.

 

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 similar to foreach in C#.

The result is.

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.

 

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:

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

And the result is.

 

List operations

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

The result is the same as with the extend function.

Result.

 

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.

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:

 

List size

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

The first way is to use the len function.

The second way is to use the __len__ function.

Leave a Reply

Your email address will not be published. Required fields are marked *