Danilo Ivanovic
Danilo Ivanovic

Reputation: 1226

How do I delete every element of list of string that starts with a string from that list?

I have a list that looks like this:

  ["12", "123", "145", "178", "1264"]

I want to find a way of changing that list. If one of the string holds an already present string in the list it should be deleted. For the given list above, it has element 12 so every element that starts with 12 should be removed from the list. The list should look like this after.

["12", "145", "178"]

I have a way of solving this with loops. But I'm looking for a more Python-like solution. I was reading about list comprehensions and tried to use them to solve this but I couldn't find a solution.

Upvotes: 0

Views: 47

Answers (1)

supermodo
supermodo

Reputation: 803

Something like this?

l1 = ["12", "123", "145", "178", "1264"]
l2 = [a for a in l1 if a not in [n for n in l1 for length in range(len(n)) if n[:length] in l1]]

Upvotes: 1

Related Questions