Using lists with Python 3

Lists are the most versatile type in Python, lists can be used to store data or to implement other more complex data structures, take a look at the implementation of queues at:

python lists

A list can be created by inserting comma-separated values inside square brakets:

The empty list is [].

One of the most interesting point about python lists is that the elements of a list need not to be of the same type:

LIST_B is a valid list in python. The content of lists can be printed using the print function:

and its output is
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, ‘word’, ‘another word’, 3.01, 4, 5, 6, 7, 8, 9]

To access the elements in a list python uses the square brackets.

And its output is:

Python lists provide also the slicing

To add an element to the end of a list you can use the append method

The new list will contain [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 8]

LIST_REM=LIST_A doesn’t copy the list, to copy the list you can use slicing:

To remove an element of the list you can use the remove method:

This method removes the first occurence of the specified items, the new list will contain [0, 1, 2, 3, 4, 5, 6, 7, 9, 8]

To remove an element of the list for which you know the posistion you can use the del method (and if you need you can use slicing):

To insert an element into a list you can use the insert method. For example to add the element “100” in the middle of the list:

Two methods are very useful, reversed and sorted. both return a new list the first is reversed and the second is sorted:

You can find the full source code on my github at

The class List provides the following methods:

list.append(x) Add an item to the end of the list. Equivalent to a[len(a):] = [x].
list.extend(iterable) Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable.
list.insert(i, x) Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
list.remove(x) Remove the first item from the list whose value is x. It is an error if there is no such item.
list.pop([i]) Remove the item at the given position in the list, and return it.
list.clear() Remove all items from the list. Equivalent to del a[:].
list.index(x[, start[, end]]) Return zero-based index in the list of the first item whose value is x.
list.count(x) Return the number of times x appears in the list.
list.sort(key=None, reverse=False) Sort the items of the list in place.
list.reverse() Reverse the elements of the list in place.
list.copy() Return a shallow copy of the list. Equivalent to a[:].



You can find the full source code of this post on my github at


Related Posts

1 thought on “Using lists with Python 3

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.