1

I am new to python and am trying to create a copy of a list without a certain element. This is how I am doing it at the moment:

oldList[1,23,4,3,5,345,4]
newList = oldList[:]
del newList[3]
doSomthingToList(newList)

I was wondering if there is a better more eloquent way to do this, instead of copying the list and then deleting the element in two lines?

Hydar77
  • 187
  • 1
  • 2
  • 9

4 Answers4

2

Using list comprehension:

>>> oldList = [1,23,4,3,5,345,4]
>>> newList = [x for i, x in enumerate(oldList) if i != 3] # by index
>>> newList
[1, 23, 4, 5, 345, 4]

>>> newList = [x for x in oldList if x != 4] # by value
>>> newList
[1, 23, 3, 5, 345]
falsetru
  • 357,413
  • 63
  • 732
  • 636
2
oldList[1,23,4,3,5,345,4]
newList = oldlist[:3] + oldList[4:]
doSomthingToList(newList)
Eugene P.
  • 2,645
  • 19
  • 23
0

Try this with 'slicing':

>>> oldList = [1, 2, 3, 4, 5]
>>> newList = oldList[:2] + [oldList[3:]
>>> newList
[1, 2, 4, 5]
Kevin
  • 2,112
  • 14
  • 15
0

Consider using the built-in function filter

oldList = [1, 2, 3, 4, 5]
newList = filter(lambda number: number != 3, oldList)

# newList == [1,2,4,5]

filter's arguments are function, iterable. It applies the function you give it to every element of the iterable and returns a list of the elements that the function returns True on.

Cody Piersall
  • 8,312
  • 2
  • 43
  • 57