4

Is there a way to do a variable assignment inside a function call in python? Something like

curr= []
curr.append(num = num/2)

3 Answers 3

8

Nopey. Assignment is a statement. It is not an expression as it is in C derived languages.

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

Comments

4

I'm pretty certain I remember one of the reasons Python was created was to avoid these abominations, instead preferring readability over supposed cleverness :-)

What, pray tell, is wrong with the following?

curr= []
num = num/2
curr.append(num)

2 Comments

Well, I see your point, but I don't see why cur.append(num=num/2) is less readable than something like [x for x in range(1000,9999) if not [t for t in range(2,x) if not x%t]]
I don't use those ones either :-) I'm more your "classical" Python user.
0

Even if you could, side-effecting expressions are a great way to make your code unreadable, but no... Python interprets that as a keyword argument. The closest you could come to that is:

class Assigner(object):
   def __init__(self, value):
      self.value = value
   def assign(self, newvalue):
      self.value = newvalue
      return self.value

 # ...
 num = Assigner(2)
 curr = []
 curr.append(num.assign(num.value / 2))

3 Comments

Why, pray tell, would you even think of the above. ;)
@msw, sometimes one's transcribing a "reference algorithm" from C to Python, for example, and in a first phase of such a transcription staying as close to the structure of the C code as feasible is an excellent idea (one refactors later to make the code decent Python, faster, etc, after one has a working Python implementation of the reference algorithms). Slightly different, but not drastically so, analogous considerations, can apply in using Python to prototype code for later transcription into C: the closer to C's structure the prototype is, the easier the transcription will be.
@alex, first of all, note the winky smiley ;), then note the lexical parallelism to the second sentence of paxdiablo's answer. Then note that the "because I can, but really, don't" of Mr. Safyan's answer and how it isn't anywhere close to the equivalent C-like expression. cf. en.wiktionary.org/wiki/levity

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.