Lists
In this lesson, you will learn about the list object and its methods in Python.
We'll cover the following...
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 objectprint("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 listprint("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 4none_list = [None] * 100 # result is 100 None’sprint("Length of none list:", len(none_list)) # Should give 100num_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
...