GEH_L
GEH_L

Reputation: 25

Slicing to remove item in the middle of the list

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?

Upvotes: 0

Views: 9894

Answers (4)

Syed Abdur Rafay
Syed Abdur Rafay

Reputation: 11

For slicing use this to remove second 8

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

Upvotes: 1

user14690153
user14690153

Reputation: 1

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

Upvotes: 0

mmartin
mmartin

Reputation: 13

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.

Upvotes: 1

TS_
TS_

Reputation: 317

If you know the index then this should work:

del nums[4:5]

Upvotes: 4

Related Questions