1

is there any shorthand method of defining multiple objects of the same class in one line. (I'm not talking about lists or array of objects)..

i mean something like

p1,p2,p3 = Point()

any suggestions?

1
  • What would that mean? Can you provide some explanation of what you think that should do? Commented Aug 1, 2011 at 20:06

4 Answers 4

6

It may be slightly more efficient to use a generator comprehension rather than a list comprehension:

p1, p2, p3 = (Point() for _ in range(3)) # use xrange() in versions of Python where range() does not return an iterator for more efficiency

There's also the simple solution of

p1, p2, p3 = Point(), Point(), Point()

Which takes advantage of implicit tuple packing and unpacking.

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

1 Comment

ya this was exactly what I wanted..thnx
3

Not really.

p1, p2, p3 = [Point() for x in range(3)]

Comments

2

What exactly are you trying to achieve?

This code does what you're asking, but I don't know if this is your final goal:

p1, p2, p3 = [Point() for _ in range(3)]

Comments

1

Think map is also acceptable here:

p1, p2, p3 = map(lambda x: Point(), xrange(3))

But generator expression seems to be a bit faster:

p1, p2, p3 = (Point() for x in xrange(3))

4 Comments

That's a generator comprehension, not a list comprehension.
@JAB: that's generator expression, not generator comprehension
@TokenMacGuy: Considering the syntax usage elsewhere in the document, "generator comprehension" can simply be taken to mean "comprehension wrapped as a generator" rather than "as a list" or "as a dict". After all, what most people refer to as "list comprehensions" are actually "(list )comprehensions contained within list displays", as shown in the link you provided.
Thank you guys - i have modified my post.

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.