Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return all list elements of a given length?

I'm trying to return words that have a specific length.

This is my code so far. words is a list and size is a positive integer.

def by_size(words, size)
    for word in words:
        if len(word) == size:

I'm not sure how to continue. by_size(['a', 'bb', 'ccc', 'dd'], 2) should return ['bb', 'dd']. Any suggestions would be of great help.

like image 664
shaarr Avatar asked Nov 02 '14 08:11

shaarr


People also ask

How do you get the length of each element in a list?

The len() function for getting the length of a list. Python has a built-in function len() for getting the total number of items in a list, tuple, arrays, dictionary etc. The len() method takes an argument where you may provide a list and it returns the length of the given list.

How do I get the length of a list of elements in Python?

Technique 1: The len() method to find the length of a list in Python. Python has got in-built method – len() to find the size of the list i.e. the length of the list. The len() method accepts an iterable as an argument and it counts and returns the number of elements present in the list.

Can you use LEN () on a list?

A list is identifiable by the square brackets that surround it, and individual values are separated by a comma. To get the length of a list in Python, you can use the built-in len() function.

What does list length return?

Description. Python list method len() returns the number of elements in the list.


2 Answers

I would use a list comprehension:

def by_size(words, size):
    return [word for word in words if len(word) == size]
like image 63
Ben Avatar answered Sep 30 '22 04:09

Ben


def by_size(words,size):
    result = []
    for word in words:
        if len(word)==size:
            result.append(word)
    return result

Now call the function like below

desired_result = by_size(['a','bb','ccc','dd'],2)

where desired_result will be ['bb', 'dd']

like image 31
R A Khan Avatar answered Sep 30 '22 03:09

R A Khan