1

I'm about to work my way into python's 3.5 lambda notation and I'm wondering wether nested loops can simply be replaced with a lambda one-liner. e.g.: I have this simple dummy class hierarchy:

class Resource:
    def __init__(self, name="foo"):
        self.name = name

class Course:
    def __init__(self):
        self.resources = list()

class College:
    def __init__(self):
        self.courses = list()

I have an instance of Collegewith multiple Courses and Resources as my starting point.

college = College()

Now if I want a listof all the Resources in my College I could easily do this with 2 for-loops:

all_resources = list()
for course in  college.courses:
    for resource in course.resources:
        all_resources.append(resource)

This is indeed very simple but I wondered whether I could also achieve this by doing something like this:

all_resources = list(map(lambda r: r, [c.resources for c in college.courses]))

But unfortunately this gives me a listof lists and not a listof Resources, what I wanted to achieve. Is lambda suitable for something like that? What would be the most pythonic way for a operation like this?

2 Answers 2

6

First of all, please stop creating empty lists by calling list() — it's both simpler and quicker to use a literal empty list [] (cheeck this with timeit if you don't believe me).

Secondly, there is absolutely no need to use lambda to create the list you want. A simple list comprehension will do the job:

all_resources = [r for r in course.resources for course in college.courses]

Don't overthink it. Keep it as simple as you can.

Sign up to request clarification or add additional context in comments.

1 Comment

I think these loops are the wrong way round? It should be: all_resources = [r for course in college.courses for r in course.resources]
2

You shouldn't be using lambdas for this. You should be list comprehensions.

all_resources = [resource for resource for course in college.courses in course.resources]

Lambdas would be completely unnecessary here. If you absolutely wanted to, you could do something like:

all_resources = []
[(lambda c: [all_resources.append(r) for r in c])(x) for x in college.courses)]

But I'd recommend the first one. An alternative giving a different order would be

all_resources = [resource for resource in course.resources for course in college.courses]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.