Lists

In this lesson, you will learn about the list object and its methods in Python.

Definition

A Python list is an indexable sequence of values, which may not necessarily all be of the same type. The first index is 0. You can create a list by writing a comma-separated sequence of values enclosed in brackets, [].

Here are a few examples of this:

Press + to interact
s = ["Mary", 23, "A+"] # List object
print("Original s", s)
name = s[0] # name is now "Mary"
print("Name:", name)
s[1] += 1 # s is now ["Mary", 24, "A+"]
print("Updated s", s)
new_s = [] # Empty list
print("Empty list:", new_s)

Arbitrary size lists

In Python, you can create a list of an arbitrary size by “multiplying” it by an integer. The integer must be to the right of the * operator.

You can observe this in the following example:

Press + to interact
zero_list = [0] * 4 # result is [0,0,0,0]
print("Length of zero list:", len(zero_list)) # Should give 4
none_list = [None] * 100 # result is 100 None’s
print("Length of none list:", len(none_list)) # Should give 100
num_list = [2,4] * 3 # result is [2,4,2,4,2,4]
print("Length of number list", len(num_list)) # Should give 6 (num_list has 2 values so 2 * 3)

Shallow copy effect in lists

Let’s assume we have a variable called x. If x is a list; and you say y = x, then y becomes another name for the same list, not a copy of x. That is, any change you make to y ...