** * This article is from Udemy "[Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style](https://www.udemy.com/course/python-beginner/" Introduction to Python3 taught by active Silicon Valley engineers + application + American Silicon Valley style code style ")" It is a class notebook for myself after taking the course of. It is open to the public with permission from the instructor Jun Sakai. ** **
>>> s = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[0] = 'A'
>>> s
['A', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[2:5] = ['C', 'D', 'E']
>>> s
['A', 'b', 'C', 'D', 'E', 'f', 'g']
You can directly assign a character string by specifying an index or slice in the list.
.append ()
and .insert ()
>>> n = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n.append(100)
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
>>> n.insert(0, 200)
>>> n
[200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]
.append
adds a string to the end of the list.
You can use .insert
to specify an arbitrary index and insert a string at that location.
◆.pop()
>>> n = [200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n
[200, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n.pop(0)
200
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 300]
>>> n.pop()
300
>>> n
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
If you specify an index with .pop ()
, that element will be extracted.
The extracted elements disappear from the list.
If no index is specified, the last element will be extracted.
>>> s = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> s[2:5] = []
>>> s
['a', 'b', 'f', 'g']
You can delete an element by replacing the specified part with an empty list.
del
)>>> n = [1, 2, 3, 4, 5]
>>> n
[1, 2, 3, 4, 5]
>>> del n[0]
>>> n
[2, 3, 4, 5]
>>> del n
>>> n
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
You can delete the indexed one with del
.
Note that if you inadvertently multiply n
by del
without specifying an index, n
itself will be deleted.
.remove ()
)>>> n = [1, 2, 3, 4, 5]
>>> n
[1, 2, 3, 4, 5]
>>> n.remove(2)
>>> n
[1, 3, 4, 5]
>>> n.remove(4)
>>> n
[1, 3, 5]
>>> n.remove(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
You can use .remove ()
to directly specify and remove an element.
At this time, if an element that does not exist in the list is specified, an error will occur.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> x = a + b
>>> x
[1, 2, 3, 4, 5, 6]
This is as I did before.
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> a += b
>>> a
[1, 2, 3, 4, 5, 6]
+ =
Adds the elements in the list of b
to the list of ʻa`.
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
You can also use a method called .extend ()
.
Recommended Posts