Python Forum
Don't understand why this quicksort code works
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Don't understand why this quicksort code works
#6
Because the data structure is a list, which is mutable. When you assign something to a variable (x = 42), the old value of the variable still exists, but there's a new binding to the new value. But with lists, the actual variable was never reassigned, the only thing that changed was the contents of the list.

Using your example...
>>> def f(x):
...   x[0] = x[0] * 2
...   return "unrelated string"
...
>>> x = [5, 4, 3, 2, 1, 0]
>>> f(x)
'unrelated string'
>>> x
[10, 4, 3, 2, 1, 0]
>>> # but if we were to re-assign x, instead of using an element...
...
>>> def f(x):
...   x = ['green', 'eggs', 'and', 'spam']
...   return 0
...
>>> x
[10, 4, 3, 2, 1, 0]
>>> f(x)
0
>>> x
[10, 4, 3, 2, 1, 0]
Reply


Messages In This Thread
RE: Don't understand why this quicksort code works - by nilamo - Mar-26-2018, 08:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable to understand the meaning of the line of code. jahuja73 0 399 Jan-23-2024, 05:09 AM
Last Post: jahuja73
  My code works on Jupyter Lab/Notebook, but NOT on Visual Code Editor jst 4 1,296 Nov-15-2023, 06:56 PM
Last Post: jst
  Code works but doesn't give the right results colin_dent 2 806 Jun-22-2023, 06:04 PM
Last Post: jefsummers
  Code used to work 100%, now sometimes works! muzicman0 5 1,581 Jan-13-2023, 05:09 PM
Last Post: muzicman0
  Pyspark - my code works but I want to make it better Kevin 1 1,873 Dec-01-2021, 05:04 AM
Last Post: Kevin
Question email code works in 2.7 but not in 3 micksulley 3 2,675 Nov-04-2021, 09:44 PM
Last Post: micksulley
  My simple code don't works !! Nabi666 1 1,658 Sep-06-2021, 12:10 PM
Last Post: jefsummers
  HackerRank Problem: Code works on VS Code but not on the HackerRank site Pnerd 3 2,777 Feb-28-2021, 07:12 PM
Last Post: Pnerd
Question Google Foobar- Code works in my IDE but not in foobar. Static method? pr3ttykitty 4 5,053 Feb-24-2021, 05:03 PM
Last Post: nilamo
  Unable to understand how given code takes a fixed input value, without inputting. jahuja73 4 2,820 Jan-28-2021, 05:22 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020