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
  • 45,811
  • 27
  • 120
  • 136
Chris
  • 25,362
  • 24
  • 71
  • 129

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
  • 45,811
  • 27
  • 120
  • 136
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
  • 906
  • 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
  • 82,977
  • 18
  • 174
  • 164
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,384
  • 14
  • 18