0

I'm new to Python and I'm trying to understand some basic thing. I have this code:

def mix_up(a, b):
    a,b=b[0:2]+a[2:], a[0:3]+b[3:]
    print (a,b)

mix_up("abcd","efgh")

why b doesn't get the "new" 3 letters of a (i.e, "efch")? Is there an elegant of doing it in one line, or I have to use other variables?

Thanks!

sagivmal
  • 86
  • 1
  • 2
  • 9
  • The assignment, also for tuple assignments, happens after the right hand side has been *completely* evaluated, i.e. `a[0:3]` evaluates against the unmodified `a`. Can you describe what you want to achieve? – dhke Jun 09 '16 at 11:08
  • @BhargavRao I'd have considered it *close enough*. But there are no side effects here, just plain old right-to-left. – dhke Jun 09 '16 at 11:11
  • what is the problem with doing it like this " a = b[0:2]+a[2:] b = a[0:3]+b[3:]" ? – sumit Jun 09 '16 at 11:17

1 Answers1

0

The reason its not working is because the assignment (the left hand side of =) only happens after the entire right hand side is evaluated.

So your a and b are still the "old" a and b in the statement, and not the new ones.

To fix it, simply split it into two statements:

a = b[0:2]+a[2:]
b = a[0:3]+b[3:]  # now this is the "new" a
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284