Search code examples
pythonlisttupleszipenumerate

How to remove item from enumerated list of tuples


Let's say I have two lists of names and birth years, then I decide to zip them enumerate them, like so:

names = ['Boris', 'Billy', 'Tod']
dates = ['1990', '1992', '1994']

pairs = list(zip(names,dates))
pairs_num = list(enumerate(pairs,start=1))

What if, at this point, I need to remove one of the items in pairs_num knowing just the name, e.g. 'Boris'. How do I go about that?


Solution

  • This is one approach using filter.

    Ex:

    names = ['Boris', 'Billy', 'Tod']
    dates = ['1990', '1992', '1994']
    
    pairs = list(zip(names,dates))
    pairs_num = list(enumerate(pairs,start=1))
    print(list(filter(lambda x: x[1][0] != 'Boris', pairs_num)))
    

    Output:

    [(2, ('Billy', '1992')), (3, ('Tod', '1994'))]
    

    But it would be better if you had a dict instead of a list. That way you can delete the item by using name as key.