Python list manipulation
List join => extend ()
| How to write |
Contents |
| s.extend(t) |
Add the contents of t to the object s |
| s += others |
s.extend(others)Will have the same result as |
Add element at specified position => insert ()
| How to write |
Contents |
| s.insert(i,x) |
I of object s(index)Insert x at the position specified by |
Delete the element specified by the index => del
| How to write |
Contents |
| del s[i:j] |
Delete elements from indexes i to j |
Remove an element whose position you do not know => remove ()
| How to write |
Contents |
| s.remove(x) |
Remove the first element that matches x from s |
Know the index of an element => index ()
| How to write |
Contents |
| s.index(x) |
Returns the index where x first appears in s |
Is there a value => in
| How to write |
Contents |
| x in s |
Returns True if the element of object s has x, False otherwise |
How many values are in the list => count ()
| How to write |
Contents |
| s.count(x) |
Returns the number of times x appears in s |
Sorting elements => sort ()
List (list) Sort elements with a method dedicated to objects
| How to write |
Contents |
| s.sort() |
Sort the elements of s in ascending order |
| s.sort(reverse=True) |
Sort the elements of s in descending order |
Copy of list
a = [1,2,3]
b = a
print(b)
a[0] = 'Hogehoge'
print(a)
print(b)
result
[1,2,3]
['Hogehoge',2,3]
['Hogehoge',2,3]
The operation for list a is also reflected in list b → "Substitution of reference"
To make a "real copy of the list"
- Use the copy () method
- Use the list () function
- Slice the list to create a new list
a = [1,2,3]
b = a.copy()
c = list(a)
d = a[:]
a[0] = 'Hogehoge'
print(a)
print(b)
print(c)
print(d)
result
['Hogehoge',2,3]
[1,2,3]
[1,2,3]
[1,2,3]