How to delete list items from list in python


I have a list with strings and super script characters(as power).
I need to concatenate scripted values with strings.
But according to my coding part It repeating same value twice.
I have no idea to remove unnecessary values from the list.

my original list –>

separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']

result according to my coding part –>

result = ['N', 'm', 'm⁻²⁴', 'kJ', 's', 's⁻¹', 'km', 'km⁻²¹', 'kJ', 'kJ⁻²', 'm', 'kJ⁻²']

I expected result –>

 result = ['N', 'm⁻²⁴', 'kJ', 's⁻¹',  'km⁻²¹',  'kJ⁻²', 'm', 'kJ⁻²']

I tried to delete last index when concatenate two items.But It gave me an error.

–> del (separating_units[(separate_units.index(su) – 1)]) # grab the last (index of unit) value to delete from the list.

Error coding part –>

def power_set_to_unit():
    result = [su if su.isalpha() else del (separating_units[(separate_units.index(su) - 1)]) (separate_units[(separate_units.index(su) - 1)] + su) for su in separate_units]

I prefer to do this in single line coding part.
Please help me to do this…

Asked By: sonny



Inside the function power_set_to_unit, you can iterate deciding whether to start a new entry in result, or append to the last element if you found an exponent:

separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']

def power_set_to_unit():
    result = []
    for x in separate_units:
        if x.isalpha():
            result[-1] += x
    return result

# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']

PS. One-liner:

power_set_to_unit = lambda sep='n': ''.join((sep+x if x.isalpha() else x) for x in separate_units).split(sep)[1:]
# ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']

The basic idea is to add a separator between characters when a exponent is not detected.

Answered By: C-3PO

Here is another oneliner using list comprehension and zip for a look ahead:

separate_units = ['N', 'm', '⁻²⁴', 'kJ', 's', '⁻¹', 'km', '⁻²¹', 'kJ', '⁻²', 'm', '⁻²']

[a if b.isalpha() else a + b for (a,b) in zip(separate_units[:-1], separate_units[1:]) if a.isalpha()]
# should result in ['N', 'm⁻²⁴', 'kJ', 's⁻¹', 'km⁻²¹', 'kJ⁻²', 'm⁻²']

To answer the question in the title of your post, to delete an item in list comprehension put the filter in an if-condition that follows the forin block. For example, to get rid of non-alphabetic strings in a string list string_list just use

[x for x in string_list if x.isalpha()]
Answered By: Dmitri Chubarov
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.