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

90 views Asked by At

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))
2

There are 2 answers

0
Pranjal Doshi On BEST ANSWER

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.

0
thetaco On

You have a line that says

if len(movies)<minlen:

That never allows your code to execute. You broke your movies into a list of lists, and use

for movies in my_movies:

This line iterates through the embedded lists, all of which are longer than length 2, meaning that len(movies) is never less than minlen and all_small_movies remains empty.