![]() |
|
[Tut] Python Slice Remove First and Last Element from a List - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] Python Slice Remove First and Last Element from a List (/thread-99716.html) |
[Tut] Python Slice Remove First and Last Element from a List - xSicKxBot - 07-18-2022 Python Slice Remove First and Last Element from a List 5/5 – (1 vote) Problem Formulation Question: Given a Python list stored in a variable Code: lstCode: lstExample: The list Code: ['Alice', 'Bob', 'Carl', 'Dave']Code: lstCode: ['Bob', 'Carl']Method 1: Slicing List[1:-1] To remove the first and last elements from a Python list, use the expression Code: lst = lst[1:-1]Code: variable[start:stop]Code: startCode: stopCode: stopCode: -iHere’s an example: Code: lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst = lst[1:-1]
print(lst)
# ['Bob', 'Carl']This code snippet removes the first element Code: 'Alice'Code: 'Dave'Note that this approach also works for lists with one element: Code: lst = ['Alice']
lst = lst[1:-1]
print(lst)
# []… and also for an empty list with zero elements: Code: lst = []
lst = lst[1:-1]
print(lst)
# []Feel free to get some background on slicing by watching the following tutorial: Learn More: An Introduction to Python SlicingMethod 2: Slicing List Without Negative Index To remove the first and last elements from a Python list, you can also use the slightly more complex expression Code: lst = lst[1:len(lst)-1]Code: len()Here’s an example: Code: lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst = lst[1:len(lst)-1]
print(lst)
# ['Bob', 'Carl']You can watch my related tutorial video: Learn More: The Python Code: len()Method 3: list.pop() and list.pop(0) To remove the first element of a Python list, you can use the Code: list.pop(0)Code: list.pop()Here’s a minimal example: Code: lst = ['Alice', 'Bob', 'Carl', 'Dave']
lst.pop() # remove last
lst.pop(0) # remove first
print(lst)
# ['Bob', 'Carl']However, for a list with less than two elements, this will raise an Code: IndexError: pop from empty listCode: ifHere’s some background info in case you want to dive deeper into this approach: The Code: list.pop()Code: listCode: list.pop(index)Code: indexCode: index Learn More: The Python Code: list.pop()Summary You’ve learned the three easy ways to remove both the first and last elements from a Python list:
Thanks for your interest in learning with Finxter! You can check out our free email academy here: |