-1

I have a really large list of like 3 million elements, say it's

x = [1, 2, 3, 4, 5, 6, ..., 3000000]

and I have tried subtracting a number from it, like 8, (inputting exactly like this: x - 8) and it thankfully gives me another list of the same amount of elements but with 8 subtracted from it Like

[-7, -6, -5, -4, -3, -2, ..., 2999992]

but I have another list, say

otherlist = [1, 2, 3, 4, 5, 6, 7, 8]

where otherlist[7] = 8 and when I try to perform the same subtraction (x - otherlist[7]) it freaks out on me & can't just give me the same output as before.

How can I approach this problem? I have tried creating a separate list of just

separatelist = [0, 1, 2, ..., 2999999]

for example so I could use it as indices to iterate over my original x list

x[m] - otherlist[7] for m in separatelist

but that has the same issue of not processing.

Calaf
  • 1,133
  • 2
  • 9
  • 22
moeur
  • 9
  • 1
  • 4
  • 2
    Are you using numpy? Usually, subtracting a number from a list is not a supported operation. It could possibly work if the list is a numpy array – Omer Tuchfeld Aug 03 '20 at 18:21
  • ``x - 8`` is *not* a valid operation for the ``x`` shown here. Note that you don't need a list of indices to traverse a list – you can just do ``for element in list`` or, if you need the index e.g. for modification, ``for index, element in enumerate(list)``. – MisterMiyagi Aug 03 '20 at 18:31

2 Answers2

2

You can use numpy for subtracting elements. It's faster using numpy.

In [107]: import numpy as np
In [108]: lst = np.array(range(3000000))

In [109]: otherlist = np.array([1, 2, 3, 4, 5, 6, 7, 8])

In [110]: lst - otherlist[-1]
Out[110]: array([     -8,      -7,      -6, ..., 2999989, 2999990, 2999991])

OR

using lists only will be slow

In [115]: otherlist = [1, 2, 3, 4, 5, 6, 7, 8]

In [116]: lst = list(range(3000000))

In [117]: [x - otherlist[-1] for x in lst]
bigbounty
  • 16,526
  • 5
  • 37
  • 65
1

if you mean like remove the number 8 from the list then u can use the remove function

x.remove(8)

or if u want to subtract all numbers by 8 then:

x = [1, 2, 3, 4, 3000000]

y = []

for num in x:
    subtracted = num - 8
    y.append(subtracted)

print(y)