Home > Blockchain >  How do I delete certain elements of my list?
How do I delete certain elements of my list?

Time:03-26

So I've got a list that looks like this: ['87','88','89',...,'98','99'].

I want to check if there's a a number in this list that can be paired, like '89' and '98'. If there's such a number, I would want to remove it from the list and determine the length of the customised list. I've tried this but without success:

for j in range(len(list)):
    if list[j][::-1] in list:
        length -= 1

The customised list should look something like this: ['87','88','89',...,'97','99']

I've set the length of my list at the beginning of my code equal to 0 so my variable isn't the problem. Can someone help me with this problem? I'm pretty new to Python. Thanks in advance!

CodePudding user response:

Form new list with only first elements from reverse pairs.

myList = ['87','88','89','98','99']
newList = []
for el in myList:
  if el[::-1] not in newList:
    newList.append(el)
print(len(newList))

Or complex check for original list

myList = ['87','88','89','98','99']
for el in myList[:]:
  if el in myList and el[::-1] in myList and el != el[::-1]:
    myList.remove(el[::-1])
print(len(myList))

Or only length finding. Counting each pair twice, because condition is true for first and second elements in pair.

myList = ['87','88','89','98','99']
pairsCount = 0
for el in myList[:]:
  if el in myList and el[::-1] in myList and el != el[::-1]:
    pairsCount  = 1
print(len(myList) - pairsCount // 2)

CodePudding user response:

If you still want to keep the palindromes like "88":

new_list = []
for v in my_list:
    if v[::-1] == v:
        new_list.append(v)
    elif v[::-1] not in my_list:
        new_list.append(v)

print(len(new_list))

Example

my_list = ['87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99']

Output

['87', '88', '90', '91', '92', '93', '94', '95', '96', '97', '99']

Both "89" and "98" are removed but palindromes like "88" are kept.

CodePudding user response:

What I can think of is something like what follows:

myList = ['87','88','89','98','99']
[x for i,x in enumerate(myList) if x[::-1] not in myList[:i]]

Output

['87', '88', '89', '99']

Note that, in this answer, numbers like 99 will not be selected in the output since their corresponding palindromes are themselves.

And If you are interested in the length of the list, you can do something like:

len([x for i,x in enumerate(myList) if x[::-1] not in myList[:i]])

Output

4
  • Related