2024年3月8日 星期五

[Python] Remove elements from a list

.
[Python] Remove elements from a list
.

(1) Using the del keyword
(2) Using the list.remove(x) method
(3) Using the list.pop([x]) method

... ... ...
(1) Using the del keyword:
# Sample Code 1
list1 = [0, 1, 2, 3, 4, 5, 6]
del list1[0]
print(list1)
# [1, 2, 3, 4, 5, 6]

del list1[-1]
print(list1)
# [1, 2, 3, 4, 5]

del list1[:2]
print(list1)
# [3, 4, 5]


(2) Using the list.remove(x) method:
# Sample Code 2
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.remove(2)
print(list1)
# [0, 1, 3, 4, 5, 6]


(3) Using the list.pop([x]) method:
# Sample Code 3
list1 = [0, 1, 2, 3, 4, 5, 6]
list1.pop()
print(list1)
# [0, 1, 2, 3, 4, 5]
list_removed = list1.pop(4)
print(list1)
# [0, 1, 2, 3, 5]


// End

[Python] Concatenate Lists / Merge Lists in Python

.
[Python] Concatenate Lists / Merge Lists in Python
.

(1) Concatenating Lists with "+" Operator
(2) Utilizing the Extend() Method
(3) Applying the Itertools.chain() Function
(4) Native Method for List Concatenation (list.append())
(5) List Comprehension to concatenate lists

... ... ...