26

I saw there are several topics on removing items from a list, including using remove(), pop(), and del. But none of these is what I am looking for, since I want to get a new list when the items are removed. For example, I want to do this:

a = [1, 2, 3, 4, 5, 6]
<fill in >       # This step somehow removes the third item and get a new list b and let
b = [1, 2, 4, 5, 6]

How can I do this?

9
  • So what exactly is wrong with a.pop(2)? Commented Nov 21, 2016 at 10:01
  • 2
    @barakmanos i believe it returns element and not new list object as OP want it. Commented Nov 21, 2016 at 10:05
  • @khelwood OP wants to create new list without the 3rd item, not without the int 3 Commented Nov 21, 2016 at 10:07
  • 2
    b = a[:2]+a[3:] Commented Nov 21, 2016 at 10:08
  • 1
    b=a[:];b.pop(2) ??? Commented Nov 21, 2016 at 10:15

1 Answer 1

46

If you want to have a new list without the third element then:

b = a[:2] + a[3:]

If you want a list without value '3':

b = [n for n in a if n != 3]
Sign up to request clarification or add additional context in comments.

1 Comment

b = a[:2] + a[3:] it is. Thanks @Yevhen. I thought Python has something built-in function to do this, well, maybe not. But this is an excellent solution!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.