How to remove elements in a list after a specific element in Python list (slice not applicable)

Viewed 764

I have a python list shown below. I want to remove all the elements after a specific character ''

Note1: The number of elements before '' can vary. I am developing a generic code.

Note2: There can be multiple '' I want to remove after the first ''

Note3: Slice is not applicable because it supports only integers

Can someone please help me with this?

Thank you very much.

['iter,objective,inf_pr,inf_du,lg(mu),||d||,lg(rg),alpha_du,alpha_pr,ls',
 '0,8.5770822e+000,1.35e-002,1.73e+001,-1.0,0.00e+000,-,0.00e+000,0.00e+000,0',
 '1,8.3762931e+000,1.29e-002,1.13e+001,-1.0,9.25e+000,-,9.86e-001,4.62e-002f,2',
 '5,8.0000031e+000,8.86e-010,1.45e-008,-5.7,1.88e-004,-,1.00e+000,1.00e+000h,1',
 '6,7.9999994e+000,1.28e-013,2.18e-012,-8.6,2.31e-006,-,1.00e+000,1.00e+000h,1',
 '',
 'Number,of,Iterations....:,6',
 '',
 '(scaled),(unscaled)',
 'Objective...............:,7.9999994450134029e+000,7.9999994450134029e+000',
 'Dual,infeasibility......:,2.1781026770818554e-012,2.1781026770818554e-012',
 'Constraint,violation....:,1.0658141036401503e-013,1.2789769243681803e-013',
 'Complementarity.........:,2.5067022522763431e-009,2.5067022522763431e-009',
 'Overall,NLP,error.......:,2.5067022522763431e-009,2.5067022522763431e-009',
 '',
 '',
3 Answers
list = ['a', 'b', 'c', '', 'd', 'e']
list = list[:list.index('')]
#list is now ['a', 'b', 'c']

Explanation: list.index('') finds the first instance of '' in the list. list[:x] gives the first x elements of the list. This code will throw an exception if '' is not in the list.

You have a list and want to delete everything after a value that meets some sort of criteria. You can enumerate the list, searching for that value and delete the remaining slice. list.index will tell you the index of value that exactly matches some object like "".

test = ["foo", "bar", "" "baz", "", "quux"]
try:
    del test[test.index("")]
except ValueError:
    pass

If you have a more complex criteria, you can do your own scan

test = ["foo", "bar", " % " "baz", "", "quux"]
for i, val in enumerate(test):
    if "%" in val:
        del test[i:]
        break

If this list is really file, you could look for the value as you read and short-circuit.

test = []
with open("foo.txt") as f:
    for line in f:
        line = line.strip()
        if line == "":
            break
        test.append(line)

    

First, you should find the first time '' shows, by using mylist.index(''). This will indeed find the first show of it, as in index()'s documentation:

Return first index of value.

Also, note the rest of the documentation:

Raises ValueError if the value is not present.

Make sure to catch the error (or add '' to the end of your list beforehand).

Now you can use slice mylist[:mylist.index('')], or if you don't want to use it:

output = []
for i in range(mylist.index('')):
    output.append(mylist[i])
mylist = output
Related