pythonempty-list

Python function keeps returning empty list [[],[],[]]


This might be a bit obvious but I'm relatively new to python.

So I was trying a small block of code to print a list containing the smallest string from each of the sublist from the following data.

my_movies = [['How I Met Your Mother', 'Friends', 'Silicon Valley'],['Family Guy', 'South Park', 'Rick and Morty'],['Breaking Bad', 'GOT', 'The Wire', 'The Last of Us']]

Surprisingly I'm getting empty list as output. Can someone please help me out with this?

def min_length(my_movies):
    all_small_movies=[]
    minlen=2
    for movies in my_movies:
        if len(movies)<minlen:
            minlen=len(movies)
            all_small_movies=[movies]
    return all_small_movies
small_new_list=list(map(min_length,my_movies))

Solution

  • Like I mentioned, it's an issue with initialization value of minlen

    here is the updated code

    import sys
    
    my_movies = [['How I Met Your Mother', 'Friends', 'Silicon Valley'],['Family Guy', 'South Park', 'Rick and Morty'],['Breaking Bad', 'GOT', 'The Wire', 'The Last of Us']]
    
    def min_length(my_movies):
        all_small_movies=[]
        minlen=minlen=sys.maxsize
        for movies in my_movies:
            if len(movies)<minlen:
                minlen=len(movies)
                all_small_movies=[movies]
        return all_small_movies
    small_new_list=list(map(min_length,my_movies))
    
    print(small_new_list)
    
    

    Here is the output

    [['Friends'], ['Family Guy'], ['GOT']]
    

    You can obviously see that you're appending a list into list. You can modify it's behavior according to your requirement.

    It also takes first smallest string, if there are multiple smallest string of same size it will ignore other. You can decide what you want to do and update this accordingly.

    Also try to use debugger before posting issues, it will be great learning for you.