
Here are 9 list methods that beginners should remember.
Table of Contents(目次)
append()
The append()
method is the most basic operation to add a single element to a list.
The syntax is sample_list.append(x)
, which adds an element to the end of the list. It behaves the same as sample_list[len(a):] = [x]
, but using the method results in simpler and more readable code.
sample_list = ['a', 'b', 'c']
sample_list.append('d')
print(sample_list) # ['a', 'b', 'c', 'd']
Note that the append()
method inserts iterable data as-is, without expanding it. Try the following code to see this behavior.
sample_list = ['a', 'b', 'c']
sample_list.append(['d', 'e'])
print(sample_list) # ['a', 'b', 'c', ['d', 'e']]
Be aware that append()
modifies the original list destructively. This means it directly changes the original list and cannot be undone. If you might need to revert the list, consider copying it first. (Copying lists is covered in a dedicated lecture.)
insert()
The insert()
method allows you to add an element at any position.
If you are adding a new element at the end, append()
is simpler and clearer. Use insert()
when adding elements at positions other than the end.
The syntax is sample_list.insert(n, x)
, which inserts element x
at index [n]
.
sample_list = ['a', 'b', 'c']
sample_list.insert(1, 'ab')
print(sample_list) # ['a', 'ab', 'b', 'c']
This code inserts 'ab'
at index [1]
. Elements after the specified position shift one place to the right, so 'b'
and 'c'
move one position right.
Like append()
, insert()
inserts iterable data as-is without expanding. Try this code:
sample_list = ['a', 'b', 'c']
sample_list.insert(1, ['aa', 'bb'])
print(sample_list) # ['a', ['aa', 'bb'], 'b', 'c']
Notes for insert()
:
- Like
append()
, this operation modifies the list destructively. - You can use negative indexes like
[-1]
to specify positions. sample_list.insert(len(sample_list), x)
adds to the end, but if the position is always the end,append()
is clearer.
extend()
The extend()
method adds elements to the end, but differs from append()
and insert()
:
- Requires an iterable as the argument
- Expands and adds the iterable elements
Syntax: sample_list.extend(iterable)
expands the iterable and appends its elements. It behaves like sample_list[len(a):] = iterable
, but using the method makes it clearer that the elements are expanded.
sample_list = ['a', 'b', 'c']
sample_list.extend(['d', 'e', 'f'])
print(sample_list) # ['a', 'b', 'c', 'd', 'e', 'f']
Notes for extend()
:
- Passing a non-iterable (like a number) to
extend()
causes an error. - Like
append()
andinsert()
, it destructively updates the original list.
remove()
The format of the remove()
method is sample_list.remove(x)
, which removes the first element with a value equal to x
.
sample_list = ['a', '--', 'b', 'c']
sample_list.remove('--')
print(sample_list) # ['a', 'b', 'c']
Notes for remove()
:
- If multiple
x
values exist, only the first is removed; others remain. - Specifying a non-existent element raises an error.
- Destructive updates that directly change the contents of the list.
To remove all multiple values without errors, you should write the code as follows. (This includes while
, which you have not learned yet. This code will be covered in the lecture on while
.)
sample_list = ['a', '--', 'b', 'c', '--']
while '--' in sample_list:
sample_list.remove('--')
print(sample_list) # ['a', 'b', 'c']
To check whether element x
exists in list, write as follows. (Details are explained in the “Control Flow” section.)
'--' in sample_list
The syntax x in sample_list
returns True
if x
exists, False
otherwise.
In addition to while
, you can use if
statements to branch processing based on the presence or absence of element x
. (if
statements are explained in detail in the “Control Flow” section.)
sample_list = ['a', '--', 'b', 'c']
if '--' in sample_list:
# Processing when elements exist
print("'--' is in the list.")
else:
# Processing when an element does not exist
print("'--' is not in the list.")
pop()
The pop()
method removes the element at the position specified by the index from a list and returns the removed value. You can specify the index using negative numbers like [-1]
.
Notes for pop()
:
- If no index is specified,
sample_list.pop()
removes the element at the end of the list. - If the list is empty (has 0 elements) or the specified index is out of range, an error occurs.
- The list is modified directly; this is a destructive update.
# If no index is specified, remove the last element
sample_list = ['a', 'b', 'c']
result = sample_list.pop()
print(sample_list) # ['a', 'b']
print(result) # 'c' (returns the removed element)
#======================
# Remove a specific element by index
sample_list = ['a', 'b', 'c']
result = sample_list.pop(1)
print(sample_list) # ['a', 'c']
print(result) # 'b' (returns the removed element)
In the first example above, no argument is passed to the pop()
method, so the last element is removed. The removed value is assigned to the variable "result".
In the second example, an index is specified with pop(1)
. In this case, sample_list[1]
is removed, and the removed value is assigned to "result".
To prevent errors when removing an element with pop(n)
, you can use one of the following two methods:
# Check if the element exists and the index is within range
sample_list = ['a', 'b', 'c']
index = 2
length = len(sample_list)
if sample_list and -length <= index < length:
result = sample_list.pop(index)
else:
result = None
print(sample_list)
print(result)
#======================
# Use try-except to handle errors
sample_list = ['a', 'b', 'c']
index = -4
try:
result = sample_list.pop(index)
except IndexError:
result = None
print(sample_list)
print(result)
Both of these examples include concepts you haven't learned yet, so review them after completing the "Control Flow" section. For now, it is enough to understand that 'pop(n)
can raise an error depending on the condition, but there are ways to prevent it.'
index()
The index()
method searches for the specified value in a list and returns the index of the first occurrence. If the value does not exist in the list, an error occurs.
There are three ways to call index()
: passing only the value to search for, passing the value and a start
index, or passing the value with both start
and end
indexes.
index(x)
- Searches for
x
in the entire list.
- Searches for
index(x, start)
- Searches for
x
inlist[start:]
.
- Searches for
index(x, start, end)
- Searches for
x
inlist[start:end]
.
- Searches for
The optional arguments "start" and "end" are interpreted as slice notation to specify the search range. The returned index is relative to the start of the list, not relative to start.
First, let's look at an example without specifying start and end.
sample_list = ['a', 'b', 'c', 'a']
result = sample_list.index('a')
print(result) # 0 (index() returns the position of the element)
The result is "0", returning the index of the first occurrence of 'a'
.
Next, let's look at an example where only start is specified.
sample_list = ['a', 'b', 'c', 'a']
result = sample_list.index('a', 1)
print(result) # 3 (index() returns the position of the element)
In this case, the search is performed on sample_list[1:]
. The first 'a'
([0]
) is ignored, and the second 'a'
([3]
) is found. The result is "3".
Finally, let's look at an example specifying both start and end.
sample_list = ['a', 'b', 'c', 'a']
result = sample_list.index('a', 1, 3)
print(result) # error (index() raises an error if the element is not found in the specified range)
Here, the search is within sample_list[1:3]
. The first 'a'
([0]
) is ignored, and the second 'a'
([3]
) is outside the range, so an error occurs. To search until the last element, omit the end argument.
count()
The count()
method returns the number of elements in a list equal to the specified value.
sample_list = ['a', 'b', 'c', 'a']
result = sample_list.count('a')
print(result) # 2
In this example, there are two 'a'
elements, so the result is "2".
If the element does not exist, count()
returns "0" instead of raising an error.
sample_list = ['a', 'b', 'c', 'a']
result = sample_list.count('z')
print(result) # 0
sort()
Basic Usage of sort()
The sort()
method sorts a list in ascending order. To sort in descending order, use reverse=True
. (The usage of arguments like reverse=True
is explained in detail in the "Function Arguments" lecture of the "Control Flow" section.)
The sort()
method modifies the original list directly, which is a destructive update.
# Sort in ascending order
sample_list = ['c', 'a', 'b', 'e', 'd', 'h', 'g', 'j', 'i', 'f']
sample_list.sort()
print(sample_list) # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
# Sort in descending order
sample_list = ['c', 'a', 'b', 'e', 'd', 'h', 'g', 'j', 'i', 'f']
sample_list.sort(reverse=True)
print(sample_list) # ['j', 'i', 'h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
The key Argument of sort()
The sort()
method can take a "key" argument.
Without key, elements are compared directly (default behavior). By specifying it, you can derive comparison keys from each element. For example, using key=str.lower
converts all strings to lowercase before sorting, without changing the original list elements.
First, let's run the code without specifying "key".
sample_list = ['c', 'C', 'A', 'b', 'a', 'B']
sample_list.sort()
print(sample_list) # ['A', 'B', 'C', 'a', 'b', 'c']
In this case, sample_list contains uppercase 'A'
, 'B'
, 'C'
and lowercase 'a'
, 'b'
, 'c'
. Sorting as-is results in ['A', 'B', 'C', 'a', 'b', 'c']
, with uppercase letters first. This is expected behavior, as programming languages sort according to character codes, where uppercase comes before lowercase.
Next, let's run the code specifying "key".
sample_list = ['c', 'C', 'A', 'b', 'a', 'B']
sample_list.sort(key=str.lower)
print(sample_list) # ['A', 'a', 'b', 'B', 'c', 'C']
Here, key is set as key=str.lower
. The str.lower
method is applied to each element for comparison. Note that you do not include parentheses like lower()
; including them would call the method immediately, which is not the intended behavior.
The execution steps for sample_list.sort(key=str.lower)
are as follows:
- Generate sort keys
- Sort elements based on the lowercase key
- The final sorted list is
['A', 'a', 'b', 'B', 'c', 'C']
. The key is only used for comparison and does not affect the actual output elements.- Elements considered equal retain their original order.
Using str.lower
as the key allowed case-insensitive sorting. The key argument is used when you want to adjust the criteria for sorting list elements.
reverse()
The reverse()
method reverses the order of elements in a list. It does not sort the list. This operation modifies the original list directly, which is a destructive update.
sample_list = ['c', 'a', 'b', 'd']
sample_list.reverse()
print(sample_list) # ['d', 'b', 'a', 'c']