The + operator concatenates lists:
The * operator repeats a list a given number of times:
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
The slice operator also works on lists:
If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice contains all the items from the list. (But it’s a new list!)
A slice operator on the left side of an assignment can update multiple elements:
We can use slicing to create a new list containing all the same items that are in the old list:
Since lists are mutable, it is often useful to make a copy before performing operations that modify lists.
Python provides methods that operate on lists.
append is called on a list. It takes a value and mutates the list, adding the new element to the end:
extend is called on a list. It takes a list and mutates the first list, appending all the values in the second list to it:
This example leaves t2 unmodified.
Most list methods simply modify the list and return None. If you accidentally write t = t.append(42), t will end up containing None.
There are several ways to delete elements from a list, but we need only one: the pop method.
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
A string is a sequence of characters and a list is a sequence of values, but a list of characters is not the same as a string. To convert from a string to a list of characters, you can use list:
Because list is the name of a built-in function, you should avoid using it as a variable name. I also avoid l because it looks too much like 1. So that’s why I use t.
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:
An optional argument called a delimiter specifies which characters to use as word boundaries. The following example uses a hyphen as a delimiter:
join is the inverse of split. It takes a list of strings and concatenates the elements. join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter:
In this case the delimiter is a space character, so
join puts a space between words. To concatenate
strings without spaces, you can use the empty string,
’’
, as a delimiter.