Python List Complete Tutorial

In this section, we will learn what the List is and how to use it in Python.

What is a List in Python?

List is an object that is capable of taking more than one value.

If you’re not familiar with objects yet, consider a List as a container with the capability of holding multiple values as its elements.

A list is capable of dynamically adding or removing new elements in its body.

Python How to Create a List: Declaring a List in Python

There are two ways to create a list in Python:

1- using a pair of brackets `[]` and putting the elements in it.

2- using the `list()` function.

Here’s the syntax of using a pair of brackets:

variable = [value1, value2, valueN]

The `variable` in this syntax is just used to mention that variables can be used to point to a list. But we can create a list on the fly and use it in the target operation (like passing it as the argument to a function).

`[]`: in order to create a list, we start with the open bracket `[` and end with a closing bracket `]`.

`value1…valueN`: Now, within the body of the list, we can put the values we want that list to have.

Notes:

  • A list can have zero or more values set as its elements.
  • The number of elements are changeable and we can add or remove the elements after the list is created.
  • We can put different types of values as the elements of a list.

Example: create a list in Python

list1 = ["Ellen",True, 10, 23.33]

print(list1)

Output:

['Ellen', True, 10, 23.33]

As you can see, the list in this example has 4 values and each of them is of a different type.

Python List: Access List Elements (Items)

Before seeing how to access the elements of a list, you should know that the elements of a list are indexed where the first element has the index number 0 and the last element has the index number equal to the size of the list -1.

For example:

['Ellen', True, 10, 23.33]

In the list above, the first element, `Ellen` has the index number 0, the value `True` has the index of 1, the value 10 has the index of 2 and the value 23.33 has the index number of 3.

Now, in order to access the elements of a list, we use the name of the list (the variable that is pointing to the target list) + a pair of bracket `[]`.

Inside the bracket, we put the index number of the target element we want to access in the target list!

Note: a list also has methods (functions) that allow us to access its elements. You’ll learn more about these methods in later sections.

Example: accessing python list elements

list1 = ["Ellen",True, 10, 23.33]

list1[1] = False

list1[2] = 1000

list1[3] = "John Doe"

print(list1[1])

print(list1[2])

print(list1[3])

print(list1)

Output:

False

1000

John Doe

['Ellen', False, 1000, 'John Doe']

Note: if we access an element of a list on the left side of the assignment operator, that means we want to replace the target value with a new one. But calling an element of a list in any other places will return the current value in that index.

How to Make a List in Python: Python list() Function

As mentioned before, there’s another way of creating a list in Python and that is by using the `list()` function.

This function takes one argument and that is an iterable object or a sequence of numbers created using the range() function. Using either way, the result would be a list with the specified elements.

Example: python list with list() function

list1 = list(("One",2,True,False, "Jack"))

list2 = list(list1)

list2[0] = "Two"

print(list1)

print(list2)

Output:

['One', 2, True, False, 'Jack']

['Two', 2, True, False, 'Jack']

In this example, the `list1` variable has a variable that is created using the elements of a tuple object. Basically, we’ve passed a tuple object (which is an iterable object) as the argument of the `list()` function and so a new list is created that contains a copy of the element in the tuple object.

The second list, `list2` is created using the `list1` object. Basically, we’ve passed the `list1` as the argument to the `list()` function and so a new list is created from the elements of the `list1`. But remember, the `list()` function takes a copy of the target iterable object’s elements. That means the `list1` and `list2` in this example, each has its own independent elements.

Python List Length

In order to get the length of a list (meaning the number of elements currently exist in the target list) we use the `len()` function.

This function works not just for a List object but for other iterable objects as well (including Tuple, Dictionary, and Set).

The `len()` function takes one argument and that is the target iterable object (list in this case) that we want to take its length.

Example: python length of list

list1 = list(("One",2,True,False, "Jack"))

list2 = list(list1)

list2[0] = "Two"

list2.append("Jack")

list2.append("Omid")

print(f"The size of the list1 is: {len(list1)}")

print(f"The size of the list2 is: {len(list2)}")

Output:

The size of the list1 is: 5

The size of the list2 is: 7

Python Empty List

As mentioned before, a list can have 0 or more elements! A list with no elements is considered as an empty list.

In order to create such list all we need to do is to assign an empty pair of brackets `[]` to a variable.

Example: creating an empty list in Python

list1 = []

print(type(list1))

print(len(list1))

Output:

<class 'list'>

0

Python Index Out of Range Error

When creating a list with x number of elements (let’s say 4 elements) but then try to access to an element in an index number that does not exist for that list (let’s say calling the index number 10), we get an error that is known as “Index Out of Range”. This error basically is telling us that the index we’ve put to access an element in a list does not exist!

Example: python index out of range error

list1 = [1,2,3,4,5]

list1[100]

Output:

IndexError: list index out of range

Note that here there’s only 5 values in the list, but then we’ve tried to access the value in the index number 100, which does not exist! That’s why we got the error you see on the output.

Python Print a List

The simplest way of printing the elements of a list is to put that list as the argument of the `print()` function and that will show the elements of the list on the output stream.

But also we can use the `for` loop and traverse the elements of the target list and then print them to the output stream.

Example: print list python

list1 = ["Jack","Ellen","John","Omid","Elon"]

print(list1)

for element in list1:

print(element)

Output:

['Jack', 'Ellen', 'John', 'Omid', 'Elon']

Jack

Ellen

John

Omid

Elon

List Operations Python

In Python, we can multiply a list as well. When multiplying a list, the elements of the list will be copied by the specified number.

Example: multiplying a list in python

list1 = [1,2,3,4]

list1 = list1*3

print(list1)

Output:

[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]

Python List of Lists

As mentioned before, the value we put on a list can be of any type! That includes another list as well!

Let’s see a list with other lists as its elements.

Example: creating list of lists in Python

list1 = [
    [1,2,3,4],
    ["Jack","John","Ellen"],
    [True,False,True,10,20]
]
for li in list1:
    for element in li:
        print(element)

Output:

1

2

3

4

Jack

John

Ellen

True

False

True

10

20

Python in List

Using the `in` operator and `if` statement, we can check a list to see if it has a particular value or not.

Example: checking if an item exists in a python list via in operator

list1 = ["Jack","Ellen","John","Omid","Elon"]
if "Omid" in list1:
    print("Yes the value Omid is in the list1")
else:
    print("The list1 does not have the value Omid in it")

Output:

Yes the value Omid is in the list1

More to Read:

Python List Access Items

Python List Slice

Python List Loop

Python List Comprehension

Python List Copy

Python List Join

Python List Methods

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies