0

I want to write code that uses slicing to get rid of the the second 8 so that here are only two 8’s in the list bound to the variable nums. The nums are as below:

nums = [4, 2, 8, 23.4, 8, 9, 545, 9, 1, 234.001, 5, 49, 8, 9 , 34, 52, 1, -2, 9.1, 4]

This is my code:

nums=[0:4:-1]
nums=[:4]+[5:] 

but slicing seems to remove the front or bottom part, how can we remove the middle part?

GEH_L
  • 25
  • 1
  • 3
  • 2
    Does this answer your question? [How to remove an element from a list by index](https://stackoverflow.com/questions/627435/how-to-remove-an-element-from-a-list-by-index) – Mateo Torres Nov 13 '20 at 03:14

4 Answers4

4

If you know the index then this should work:

del nums[4:5]
TS_
  • 319
  • 1
  • 5
  • 2
    Deleting a slice containing only one element is a little strange, `del nums[4]` would be more usual. But +1 anyway. – wim Nov 13 '20 at 03:20
  • @wim Yes it is strange but if you follow that pattern you can run it on an empty list without having to do an `if statement` first. assuming you dynamically check `middle = len(items) // 2`, or something similar – jamylak Nov 13 '20 at 03:31
1

I understand you're asking for a solution using slicing, but have you considered:

nums.pop(4)

Which if you already know the index will get rid of that (but show also you what you're popping out) and leave you with your nums as you want it.

mmartin
  • 13
  • 4
0

to remove elements from list using Slice nums[4:5] = []

0

For slicing use this to remove second 8

    nums=nums[:4]+nums[5:]