Python has built-in lists, so the language provides a special syntax for creating lists called list literals. For example, [1, 2]
is a list literal.
The tuples described earlier are also built into the language and created with their literals. This expression in parentheses, ("foo", 42)
, is a tuple literal.
We can create multiple lists, including an empty one:
numbers = [1, 2, 3]
strings = ["foo", "bar"]
booleans = [True, False]
empty_list = []
So far, everything looks like tuples, except that the parentheses are square instead of round.
But in the last lesson, we mentioned that lists are modifiable. They can change over time. Let's learn how to modify lists by adding elements to the end:
l = [1, 2, 3]
l.append(4)
l.append(5)
print(l) # => [1, 2, 3, 4, 5]
l.extend([6, 7, 8])
print(l) # => [1, 2, 3, 4, 5, 6, 7, 8]
Lists as objects
The above example demonstrates a new type of syntax, the object method call.
Objects are entities that can store data, including other objects. Also, objects know how to handle the data in them. Programmers say that objects have their behavior.
The behavior of an object is to provide methods — functions related to the owner object in some way. A method call is similar to a function call. The only difference is that it looks like object.method(...)
, which means we can always see which object's method we call.
We will discuss Object Oriented Programming in a different course. For now, it is enough to know that methods are like functions — they can modify objects or return information about them.
The append
and extend
methods
So in the code above, list l
is the list object, and append
and extend
are methods of the list object:
- The
append
adds an element to its list - The
extend
adds all elements of the argument list to its list
Both methods add items to the end of the list. And both of them return None
, meaning they have no result we can use. The point of calling these methods is to modify the associated object.
Beginners often make this mistake:
l = [1]
l = l.append(2)
print(l) # None
# Where is the list?
Here, on line 2, the hypothetical author wanted to store the expanded list in the variable l
, but the variable ended up with the value None
which was returned by append
.
Note that a method can always return None
and change its associated object.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.