Remove Items from Python List
Python lists provide several methods to remove items, including remove(), pop(), del statement, and clear(). Below are examples for each method.
Python lists से items हटाने के लिए कई तरीके होते हैं जैसे remove(), pop(), del स्टेटमेंट और clear()। नीचे हर method के उदाहरण दिए गए हैं।
Example 1: remove() - Remove by Value
fruits = ['apple', 'banana', 'cherry']
fruits.remove('banana')
print(fruits)
Remove 'banana' from list by value using remove().
remove() से 'banana' को list से हटाएं।
Output:
Example 2: pop() - Remove Last Item
fruits = ['apple', 'banana', 'cherry']
last_item = fruits.pop()
print(fruits)
print('Popped:', last_item)
Remove and return the last item using pop().
pop() से आखिरी item हटाएं और उसे वापस पाएं।
Output:
Popped: cherry
Example 3: pop(index) - Remove Item at Index
fruits = ['apple', 'banana', 'cherry']
item = fruits.pop(1)
print(fruits)
print('Popped:', item)
Remove and return item at index 1 using pop(1).
pop(1) से index 1 का item हटाएं और वापस पाएं।
Output:
Popped: banana
Example 4: del Statement - Remove by Index
fruits = ['apple', 'banana', 'cherry']
del fruits[0]
print(fruits)
Delete item at index 0 using del statement.
del से index 0 का item हटाएं।
Output:
Example 5: del Statement - Remove Slice
nums = [1, 2, 3, 4, 5]
del nums[1:4]
print(nums)
Delete a slice (items at index 1 to 3) using del statement.
del से index 1 से 3 तक के items हटाएं।
Output:
Example 6: clear() - Remove All Items
fruits = ['apple', 'banana', 'cherry']
fruits.clear()
print(fruits)
Remove all items from list using clear().
clear() से list के सभी items हटाएं।
Output:
Example 7: Remove Item if Exists
fruits = ['apple', 'banana', 'cherry']
item = 'banana'
if item in fruits:
fruits.remove(item)
print(fruits)
Check if item exists and remove using remove().
item होने पर उसे remove() से हटाएं।
Output:
Example 8: pop() on Empty List with Try-Except
lst = []
try:
lst.pop()
except IndexError:
print('List is empty')
Handle pop() on empty list with try-except.
खाली list पर pop() का error handle करें।
Output:
Example 9: Remove Multiple Items by Loop
nums = [1, 2, 3, 4, 5, 2]
for val in [2, 3]:
while val in nums:
nums.remove(val)
print(nums)
Remove all occurrences of 2 and 3 using loop and remove().
loop से सभी 2 और 3 को remove() से हटाएं।
Output:
Example 10: Using List Comprehension to Remove Items
nums = [1, 2, 3, 4, 5, 2]
nums = [x for x in nums if x != 2]
print(nums)
Create a new list excluding items equal to 2 using list comprehension.
list comprehension से 2 को छोड़कर नई list बनाएं।
Output: