We have summarized the ** add / remove ** methods that are important for working with lists. Basically, write the code and output result with the following code.
ex.py
code = 'code'
print(code)
# code(Output result)
To add an element to a list (array) of type list or combine another list in Python, use the list methods ʻappend (), ʻextend ()
, ʻinsert ()`. In addition, there is also a method of assigning by specifying the position with the + operator or slice.
-Append element at the end: append () -Combine another list or tuple at the end (concatenate): extend (), + operator -Add (insert) element at specified position: insert () -Add another list or tuple to the specified position (insert): Use slice
append().py
l = [0, 1, 2]
print(l)
# [0, 1, 2]
l.append(100)
print(l)
# [0, 1, 2, 100]
l.append('new')
print(l)
# [0, 1, 2, 100, 'new']
l.append([3, 4, 5])
print(l)
# [0, 1, 2, 100, 'new', [3, 4, 5]]
extend().py
l = [0, 1, 2]
l.extend([100, 101, 102])
print(l)
# [0, 1, 2, 100, 101, 102]
l.extend((-1, -2, -3))
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3]
#append()Unlike, it is stored character by character
l.extend('new')
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w']
#extend()Not a method+=But yes.
l += [5, 6, 7]
print(l)
# [0, 1, 2, 100, 101, 102, -1, -2, -3, 'n', 'e', 'w', 5, 6, 7]
insert().py
l = [0, 1, 2]
l.insert(0, 100)
print(l)
# [100, 0, 1, 2]
l.insert(-1, 200)
print(l)
# [100, 0, 1, 200, 2]
l.insert(0, [-1, -2, -3])
print(l)
# [[-1, -2, -3], 100, 0, 1, 200, 2]
insert().py
l = [0, 1, 2]
l[1:1] = [100, 200, 300]
print(l)
# [0, 100, 200, 300, 1, 2]
l[1:2] = [100, 200, 300]
print(l)
# [0, 100, 200, 300, 2]
To remove a list (array) element of type list in Python, use the list methods claer ()
, pop ()
, remove ()
. In addition, there is also a method of specifying the position / range with an index or slice and deleting it with the del
statement.
-Delete all elements: clear () -Delete the element at the specified position and get the value: pop () -Search for the same element as the specified value and remove the first element: remove () -Delete by specifying the position / range in the index slice: del
clear().py
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
l.clear()
print(l)
# []
pop().py
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(l.pop(3))
# 4
print(l.pop(-2))
# 8
#If you omit the argument and do not specify the position, delete the last element
print(l.pop())
# 9
remove().py
l = ['Alice', 'Bob', 'Charlie', 'Bob', 'Dave']
l.remove('Alice')
print(l)
# ['Bob', 'Charlie', 'Bob', 'Dave']
del.py
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
del l[6]
print(l)
# [1, 2, 3, 4, 5, 6, 8]
del l[-1]
print(l)
# [1, 2, 3, 4, 5, 6, 7, 8]
#You can delete multiple elements at once by specifying a range with a slice.
del l[2:5]
print(l)
# [0, 1, 5, 6, 7, 8, 9]
I would be grateful if you could tell me if there is any other solution.
Recommended Posts