[coding tech]#1 ways to delete specific element in a list

Jude's Sound Lab·2023년 2월 21일

Algorithm & Coding

목록 보기
1/5

ways to delete elements

using index

  1. Using the del keyword: You can delete a single element or a slice of elements from a list using the del keyword followed by the index or slice of indices to be removed. Here's an example:
my_list = [1, 2, 3, 4, 5]
del my_list[2] # remove the element at index 2 (value 3)
print(my_list) # [1, 2, 4, 5]
del my_list[1:3] # remove elements at indices 1 and 2 (values 2 and 4)
print(my_list) # [1, 5]

using value

  1. Using the remove() method: You can remove the first occurrence of a specific element in a list using the remove() method. Here's an example:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3) # remove the first occurrence of the value 3
print(my_list) # [1, 2, 4, 5]

3.Using the pop() method:

my_list = [1, 2, 3, 4, 5]
value = my_list.pop(2) # remove the element at index 2 (value 3) and get its value
print(value) # 3
print(my_list) # [1, 2, 4, 5]

using list comprehension

  1. Using a list comprehension: You can create a new list that excludes the elements you want to remove using a list comprehension. Here's an example:
my_list = [1, 2, 3, 4, 5]
my_list = [x for x in my_list if x != 3] # create a new list without the value 3
print(my_list) # [1, 2, 4, 5]
profile
chords & code // harmony with structure

0개의 댓글