20

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?

Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
user3768495
  • 4,077
  • 7
  • 32
  • 58

1 Answers1

38

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • 1
    `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! – user3768495 Nov 21 '16 at 20:39