Removing last element of list in python

How to Remove From List in Python

To remove the last value from a list in Python, use the pop() method.

nums = [100, 200, 300] nums.pop() # nums is now [100, 200]

To remove a value from a list at a specific index, use the pop() method by providing it an index.

For example, let’s remove the first element of a list:

nums = [100, 200, 300] nums.pop(0)

In addition to these, there are some alternative ways to remove items from a list in Python. Next, we are going to take a look at removing values from a Python list in more detail.

How to Remove from List in Python

There are five main ways to remove elements from lists in Python:

  1. The pop() method.
  2. The clear() method.
  3. The remove() method.
  4. The del statement.
  5. List comprehensions/filtering to remove items that meet a criterion

Here is a short cheat sheet for using these five approaches.

# 1. The pop() mehthod - remove an element at a specific index names = ["Alice", "Bob", "Charlie"] names.pop(0) # remove the first name, that is, "Alice" from the list # 2. The clear() method — wipe out the whole list numbers = [1, 2, 3, 4, 5] numbers.clear() # remove everything from the list # 3. The remove() method — removes the first occurrence of a specific string names = ["Alice", "Bob", "Charlie", "Bob"] names.remove("Bob") # Remove the first "Bob" from the list. # 4. The del statement - remove the whole list or remove a specific element from it numbers = [1, 2, 3, 4, 5] del numbers[0] # Remove the first number from the list del numbers # Destroy the whole list # 5. List comprehensions and filtering — remove elements that meet a criterion names = ["Alexander", "Rob", "John", "David", "Emmanuel"] short_names = [name for name in names if len(name) < 5] # Create a list of names less than 5 long short_names = list(filter(lambda name: len(name) < 5, names)) # Another way to create a list of names less than 5 long

Let’s go through each of these approaches in more detail with examples and simple explanations.

Читайте также:  Графический чат на python

Pop() Method

The pop() method is a built-in list method in Python. It removes and returns a value from a list. Trying to remove a non-existent item causes an error.

There are two ways you can use the pop() method in Python:

  1. Call pop() without arguments. This removes and returns the last element of a list.
  2. Call pop() with an argument. It is an integer that specifies the index at which an element is removed from the list.
names = ["Alice", "Bob", "Charlie"] names.pop() # Now names is ['Alice', 'Bob']

As another example, let’s remove the first element:

names = ["Alice", "Bob", "Charlie"] names.pop(0) # Now names is ['Bob', 'Charlie']

Remember that the pop() method returns the removed value. This is useful if you want to use the removed value somewhere.

For example, let’s print the removed value and the end result:

names = ["Alice", "Bob", "Charlie"] print(f"After removing the names list is ")
After removing Alice the names list is ['Bob', 'Charlie']

If you try to remove a non-existent item from the list, an IndexError is thrown:

names = ["Alice", "Bob", "Charlie", "Bob"] names.pop(10) # IndexError: pop index out of range

Clear() Method

The clear() deletes every item from a list.

numbers = [1, 2, 3, 4, 5] numbers.clear() # Result: []

Remove() Method

To remove the first occurrence of a specific element from a list, use the remove() method.

names = ["Alice", "Bob", "Charlie", "Bob"] names.remove("Bob") # Now the names list is: ['Alice', 'Charlie', 'Bob']

Notice how there were two elements called "Bob" in the list. Thus, only the first one was removed by the remove() method.

If you try to remove a non-existent value, an error is produced:

names = ["Alice", "Bob", "Charlie", "Bob"] names.remove("Something else") # ValueError: list.remove(x): x not in List

Del Statement in Python

The three previous ways to remove from Python lists are built-in to lists.

However, you can also use a del statement to remove items from a list. This statement is not built-in to work with lists only. You can delete other Python objects with it too.

Let’s have a look at some examples of removing values from a list using the del statement:

numbers = [1, 2, 3, 4, 5] del numbers[0] # Now numbers is: [2, 3, 4, 5]

Using the del statement, you can delete a range of items in a list.

For example, let’s remove values 2,3,4 from the list of numbers:

numbers = [1, 2, 3, 4, 5] del numbers[1:4] # Now numbers is [1, 5]

In general, to remove a slice of values, use the del statement with this syntax:

  • start is the starting index
  • end is the last index you want to remove. But due to how slicing works in Python, add one to the last index to really remove at the last index.

Remove from List Using Filtering in Python

This is not directly removing values from a list. Instead, you can create a new list where you have removed values that meet a criterion.

There are two ways to filter lists in Python:

Let’s go through both of these approaches:

List Comprehension

In case you don’t know what list comprehension is, it is a shorthand for a for loop.

For example, here you can easily see how a list comprehension can compress a for loop nicely:

numbers = [1, 2, 3, 4, 5] # Square a list of values using a for loop squared_nums = [] for num in numbers: squared_nums.append(num ** 2) # Square a list of numbers using a list comprehension squared_nums = [num ** 2 for num in numbers]

Now, just like using a regular for loop, you can use a list comprehension to filter a list.

For example, let’s remove all the odd numbers from a list of numbers using a list comprehension:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] odds = [num for num in numbers if num % 2 == 0] # [2, 4, 6, 8, 10]

Filter() Function

You can also use filter() function to filter values from a list. This creates a filter object, which you can turn to a list using the built-in list() function. This Python’s built-in method does not directly remove from the list either. Instead, it creates a copy with the filtered values.

The filter() function takes two parameters:

  1. A filtering function. This can be a lambda expression or a reference to an existing function.
  2. The list (or any other iterable) to be filtered.

Let’s see the same example of filtering odd values from a list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # filter the list of numbers odds = filter(lambda num: num % 2 == 0, numbers) # Convert filter object to a list odds = list(odds) # [2, 4, 6, 8, 10]

Conclusion

Today you learned different approaches to remove items from a list in Python. To recap, here are the five ways to do it:

  • The pop() method
  • The clear() method.
  • The remove() method
  • The del statement.
  • List comprehensions/filtering to remove items that meet a criterion

Источник

How to remove the first and last item in a list?

You don't want to remove the first and the last element of a list. According to your description you want to remove the first and the last block of characters from a space-separated string which is the one and only element of a list.

6 Answers 6

If your list is stored under my_list then this should work.

This answer seems to assume that my_list is ['Q', '0006', '005C', '0078', '0030', '0030', '0033', '0034', 'ONE_OF', '0002'] , not what is shown in the question.

I'm not sure exactly what you want since it is unclear but this should help. You actually only have a single element in that list.

Assuming all your list items are strings with spaces as delimiters, here is how you can remove the first and last group of characters from each string in the list.

>>> L = ['Q 0006 005C 0078 0030 0030 0033 0034 ONE_OF 0002 '] >>> [' '.join(el.split()[1:-1]) for el in L] ['0006 005C 0078 0030 0030 0033 0034 ONE_OF'] 

Another (quite Pythonic) way to do it is using the extended sequence unpacking feature:

>>> my_list = [1, 2, 3, 4, 5] >>> _, *my_list, _ = my_list >>> my_list [2, 3, 4] 

Another question was redirected here, asking what this line does, given that res is a list:

This uses multiple assignment and extended iterable unpacking. In Python you can do something like this:

To assign 1 to a , etc. - this is multiple assignment, assigning multiple values in a single assignment statement.

If the right side consists of an iterable, Python will 'unpack' the iterable to assign the parts. For example:

t = (1, 2, 3) # a tuple a, b, c = t # after this, a == 1, b == 2, c == 3 

However, in the given example (with c and res ), the iterable on the right doesn't have to have the same number of items as the number of targets on the left.

This is where "extended iterable unpacking" comes in. For the documentation: "allowing to specify a “catch-all” name which will be assigned a list of all items not assigned to a “regular” name."

So, in c, *res, c = res , the first element of res is assigned to c , the last element is assigned to c , but everything else from the unpacked iterable (the list in this case) is assigned to *res , which will make res a list again.

res = (1, 2, 3, 4) c, *res, c = res 

Here, you may expect res to end up as (2, 3) - but that's not the case, after running, res will be [2, 3] , a list . The assignment does not transfer the type, only the values. And the extended iterable unpacking results in res being a list after the assignment, even though the values came from a tuple.

Finally, note that nicer syntax might be:

res = [1, 2, 3, 4] _, *res, _ = res 

The use of _ makes it clear that these values are to be discarded. And it removes questions about what the value of c will be after c, *res, c = res . It's 4 , because the assignments are evaluated left to right, but it's better to be clear.

Источник

Оцените статью