Home > Mobile >  How to remove from a list in python, all but one of the elements that have equal length?
How to remove from a list in python, all but one of the elements that have equal length?

Time:12-15

I am inputting a list and it must contain only one element of a particular length.

I tried:

lst = list(input("list: "))
for i, j in lst:
    if len(j) == len(i):
        lst.remove(j)
print(lst)

It's showing this:

for i, j in lst:
ValueError: not enough values to unpack (expected 2, got 1)

And I don't know what this error means, where am I going wrong? Can you please suggest something?

CodePudding user response:

Edit: You cannot use len(). How will you know if genip or pears? Both are containing 5 characters.

Easier way to do this:

fruits = ["apples", "bananas", 'genip', "pears", "mango", 'coconut']
lst = input()
res = [i for i in fruits if i not in lst]
print(f'List after removing duplicate elements: {res}') 

Result type: genip # to remove it.

List after removing duplicate elements: ['apples', 'bananas', 'pears', 'mango', 'coconut']

CodePudding user response:

You shouldn't change the list you are looping on.

Use

for i, j in lst.copy():
    ...

instead. Or deepcopy is even better.

  • Related