Search code examples
pythonpython-3.xfinance

Can you use the Filter() function on a list to create a new list from a larger list?


I would be using the list and filter functions to create a new list containing only the odd length stock tickers. I have used lambda before doing something similar with numbers but can't seem to translate it to words. My code is below..

list1 = ["GOOGL", "IBM", "AAPL", "FB", "M", "WMT"]

list(filter(lambda item: item[0] == "odd", list1))

I want the output to be all odd length stock tickers

['GOOGL','IBM', 'M', 'WMT']

Solution

  • With filter

    print(list(filter(lambda x: len(x) % 2 == 1, list1)))
    

    With list comprehension

    print([i for i in list1 if len(i)%2==1])
    

    Output:

    ['GOOGL', 'IBM', 'M', 'WMT']