Python is widely used for both scripting and automation on Linux, as well as building web and standalone applications.
Python is designed to be easy to learn, easy to write, and easy to read. It’s a great multi-purpose programming language.
Python has several different types of arrays for storing data.
Lists are arrays which allow you to store items. Items in lists can be altered, and are stored in a specific order.
Syntax and Examples
There are several methods you can use to remove an item from a list in Python – pop(), del(), and remove(). Which one you use is based on what you want the resulting list to look like.
pop()
Removes the item at the given index in the list. Also returns the value at that index:
list = [99, 32, 44, 66, 32] popped = list.pop(2) print(popped) # 44 print(list) # [99, 32, 66, 32]
Note that:
- The index is the items position in the list. When dealing with indexes we start counting at 0, not 1! So the first item in the list is index 0, the second item is index 1, and so on
- Text following the # symbol is a comment
- Comments are ignored by Python when executing your code – allowing you to include notes about what you’re doing
del()
Removes a slice from the list in the format start:end, where start and end are indexes of items in the list:
list = [99, 32, 44, 66, 32] del list[2:3] print(list) # [99, 32, 32]
remove()
Deletes the first instance of a value found in a list:
list = [99, 32, 44, 66, 32] list.remove(3:2) print(list) # [99, 44, 66, 32]
Conclusion
Removing items from lists is a vital component of any Python application. If you’re just getting started learning Python, check out our other tutorials.