Login With Github

Python 3 List Starter Tutorial

A list is one of the most important data structures in Python. It is an ordered sequence of elements which is mutable and changeable. Each element that is inside of a list is called an item, and all the items are placed inside a square bracket [ ], separated by commas.

In general, the list in Python has the following characteristics:

  • Lists are ordered.
  • Lists can contain any arbitrary objects.
  • List elements can be accessed by index.
  • Lists can be nested to arbitrary depth.
  • Lists are mutable.
  • Lists are dynamic.

How To Create a List?

Creating a list is very simple. The following code creates a list of 5 numbers:

list2 = [1, 2, 3, 4, 5 ];

It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = [];

# list of integers
my_list = [1, 2, 3];

# list with mixed datatypes
my_list = [1, "Hello", 3.4];

Lists can even have complex objects, like functions, classes, and modules, for example:

class MyClass(object):
    def __init__(self, number):
        self.number = number

my_objects = []

for i in range(100):

At the same time, we can also create a nested list, that is, one of the list items is also a list.

# nested list
my_list = ["key", [3, 5, 9], ['b','c']];

How To Access The List

There are various ways in which we can access the elements of a list.

By Index

We can use the index operator [] to access an item in a list. Index starts from 0.

a = ['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

The indices for the elements in a are shown below:

Diagram of a Python list

Note: The index must be an integer. We can't use float or other types, this will result into TypeError.

Nested lists are accessed using nested indexing.

# Nested List
nested_list = ["Good", [1,3,0,7]]

# Nested indexing

# Output: o

# Output: 7

By Negative Index

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

For example, a negative list index counts from the end of the list:

Diagram of a Python list

my_list = ['p','r','o','b','e']

# Output: e

# Output: p


We can use the [m:n] operator to access a range of items in the list. It means that the index starts at m and ends at n, but does not contain n. For example:

>>> a = ['well', 'good', 'google', 'book', 'red', 'blue']

>>> a[2:5]
['google', 'book', 'red']

m and n can be empty or negative:

a = ['well', 'good', 'google', 'book', 'red', 'blue']

# elements beginning to 4th

# elements 6th to end

# elements beginning to end

We can also specify the slicing increment by k in a[m:n:k]. For example:

>>> a = ['well', 'good', 'google', 'book', 'red', 'blue']

>>> a[2:5:2]
['blue', 'red', 'book', 'google', 'good', 'well']

That last colon tells Python that we'd like to choose our slicing increment. By default, Python sets this increment to 1, but that extra colon at the end of the numbers allows us to specify what we want it to be.

We can reverse the list with the following code:

>>>a = ['well', 'good', 'google', 'book', 'red', 'blue']

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

Nested List

In the above examples we can see that the list can have sublists, that is, one item in the list can also be another list, and so on to arbitrary depth.

Here is an example from realpython:

>>> x = ['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']
>>> x
['a', ['bb', ['ccc', 'ddd'], 'ee', 'ff'], 'g', ['hh', 'ii'], 'j']

The object structure that x references is diagrammed below:

Nested lists diagram

x[0], x[2], and x[4] are strings, each one character long:

>>> print(x[0], x[2], x[4])
a g j

But x[1] and x[3] are sublists:

>>> x[1]
['bb', ['ccc', 'ddd'], 'ee', 'ff']

>>> x[3]
['hh', 'ii']

To access the items in a sublist, simply append an additional index:

>>> x[1]
['bb', ['ccc', 'ddd'], 'ee', 'ff']

>>> x[1][0]
>>> x[1][1]
['ccc', 'ddd']
>>> x[1][2]
>>> x[1][3]

>>> x[3]
['hh', 'ii']
>>> print(x[3][0], x[3][1])
hh ii

x[1][1] is yet another sublist, so adding one more index accesses its elements:

>>> x[1][1]
['ccc', 'ddd']
>>> print(x[1][1][0], x[1][1][1])
ccc ddd

How To Change The List

List are mutable, meaning, their elements can be changed unlike string or tuple.

We can use assignment operator (=) to change an item or a range of items. For example:

# mistake values
odd = [2, 4, 6, 8]

# change the 1st item    
odd[0] = 1            

# Output: [1, 4, 6, 8]

# change 2nd to 4th items
odd[1:4] = [3, 5, 7]  

# Output: [1, 3, 5, 7]

As we know, we can modify multiple values at once using the syntax below:

a[m:n] = <iterable>

If the number of values in <iterable> is not equal to the range, then Python will automatically grow or shrink the list.

# mistake values
odd = [2, 4, 6, 8]

# output: [2, 3, 5, 7, 'a', 8]
odd[1:3] = [3, 5, 7, 'a']

# output: [2, 'a', 8]
odd[1:3] = ['a']

How To Add Items To The List

We can add one item to a list using append() method or add several items using extend()method.

odd = [1, 3, 5]


# Output: [1, 3, 5, 7]

odd.extend([9, 11, 13])

# Output: [1, 3, 5, 7, 9, 11, 13]

We can also use + operator to combine two lists. This is also called concatenation.

The * operator repeats a list for the given number of times.

odd = [1, 3, 5]

# Output: [1, 3, 5, 9, 7, 5]
print(odd + [9, 7, 5])

#Output: ["re", "re", "re"]
print(["re"] * 3)

Furthermore, we can insert one item at a desired location by using the method insert() or insert multiple items by squeezing it into an empty slice of a list.

odd = [1, 9]

# Output: [1, 3, 9] 

odd[2:2] = [5, 7]

# Output: [1, 3, 5, 7, 9]

How To Remove Items From The List

We can use the del statement to remove the elements of the list, as in the following example:

list = ['physics', 'chemistry', 1997, 2000]
print (list)

del list[2]
print ("After deleting value at index 2 : ", list)

We can also delete the items of the specified range of the list, the code is as follows:

list = ['physics', 'chemistry', 1997, 2000]

# delete multiple items
del list[1:3] 

Even we can delete the entire list:

list = ['physics', 'chemistry', 1997, 2000]

# delete entire list
del list       

# Error: List not defined

What if we want to delete a specified list item? We can use remove() method to remove the given item or pop() method to remove an item at the given index. For example:

list = ['physics', 'chemistry', 1997, 2000]

# output ['chemistry', 1997, 2000]

# output [1997, 2000]

We can also use the clear() method to empty a list.

list = ['physics', 'chemistry', 1997, 2000]

# output []

0 Comment