Home > database >  Return just the item of a list if len(list) == 1
Return just the item of a list if len(list) == 1

Time:01-11

I have a list with possibly several items (tuples) that I need to return. But what about, in the case that I only get one item in my list, I would like to return the item itself and not a list with only one item. How could this be done?

This is my code:

def strength(self):
    values = []
    max_v = 0
    my_list = []
    for i in inspect.getmembers(self):
        if not i[0].startswith('_'):
            if not inspect.ismethod(i[1]): 
                if "name" in i:
                    continue
                values.append(i[1])
                my_list.append(i)
                max_v = max(values)
    result = [tup_item for tup_item in my_list  if tup_item[1] == max_v]
    result.sort(reverse=True)
    if len(result) > 1:               
        return tuple(result)
    else:  # in case len(result) == 1
        return result  # this is where i get a list with only one item but
                       # i would like to get just the tuple itself

CodePudding user response:

If your list only has one item, it's usually at the 0th index. Just return result[0]. I would not recommend it though, since you will have to differentiate between lists and tuples from wherever you're calling that function.

CodePudding user response:

Couldnt you just return result.get(0) if size > 0

  •  Tags:  
  • Related