squaretrousers
squaretrousers

Reputation: 21

Python: how to create a list from elements that don't meet a certain condition

I have a list of names as follows:

names = [ "Brian", "jake", "Jason", "Brad", "Tony", "jimmy", "Bobby", "Stevie"] 

And I have to make a list called small_names which contain all the names which have 4 letters or less from the list above. I'm stumped.

My initial thinking was to use a while loop but it's not working.

Upvotes: 1

Views: 126

Answers (3)

Michael
Michael

Reputation: 33

Here is another answer you might want to try if you need to provide an explaination of how the code words and do not know what lambda is, or how filters work.

list = names for item in list: if len(item) <=4: print(item)

You can change item with shortNames if you wish, and thus be able to keep a name convention that makes sense to anyone looking at your code. item is too generic and could cost you points.

Good luck with the programming classes.

Upvotes: 0

Marcin
Marcin

Reputation: 238957

You can use filter:

small_names = filter(lambda n: len(n)<=4, names)
#equivalent to: small_names = [n for n in names if len(n) <=4]

print(small_names) # ['jake', 'Brad', 'Tony']

Using for loop:

small_names = []

for n in names:
    if len(n) <= 4:
        small_names.append(n)

Upvotes: 2

pawelswiecki
pawelswiecki

Reputation: 572

I'd use list comprehension:

short_names = [name for name in names if len(name) <= 4]

Upvotes: 3

Related Questions