1

So I've got a list...

a = [1,2,3,4,5]

I can produce b without 5 by saying:

b = a[:-1]

How do I produce c without 3?

c = a[:2:]?
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Chris
  • 28,822
  • 27
  • 83
  • 158

4 Answers4

1

By adding two lists

>>> a = [1,2,3,4,5]
>>> c = a[:3-1] + a[3:]   # Explicitly mentioned 3-1 to help understand better
>>> c
[1, 2, 4, 5]

An inplace way to remove

>>> a = [1,2,3,4,5]
>>> a.pop(3-1)
3
>>> a
[1, 2, 4, 5]
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

One method is to join the two list parts together as follows

a = [1,2,3,4,5]
c = a[:2] + a[3:]
c
[1,2,4,5]
Brian Cain
  • 946
  • 1
  • 7
  • 20
1

You would need to slice twice and concatenate the lists , Example -

c = a[:2] + a[3:]  #2 being the index of element `3` in the array.

Demo -

>>> a = [1,2,3,4,5]
>>> a[:2] + a[3:]
[1, 2, 4, 5]
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

You can also just pop the index out i.e.

>>> a = [1,2,3,4,5]
>>> a.pop(2)
>>> 3
>>> print(a)
[1,2,4,5]
zsoobhan
  • 1,484
  • 15
  • 18