Python Forum
Need help with weird tuple syntax
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with weird tuple syntax
#3
nums[start], nums[i] = nums[i], nums[start]
That's convenient way to swap values in python
in slow motion this will be evaluated as follows
1. on the right hand-side create tuple with two values - nums[i] and nums[start]
2. unpack that tuple into nums[start] and nums[i]. that is called iterable unpacking. i.e. you can do something like a, b = [1, 2] in which case a=1 and b=2
Of cource nums should be mutable object (e.g. list, dict, etc.), i.e. it will not work if nums is a tuple

it's equivalent to
foo = num[i]
num[i] = num[start]
num[start] = foo
but without the need of third variable to hold one of the values temporarily
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
Need help with weird tuple syntax - by mwskz8 - Dec-13-2018, 09:34 AM
RE: Need help with weird tuple syntax - by buran - Dec-13-2018, 09:58 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Tuple generator, and function/class syntax quazirfan 3 4,201 Aug-10-2021, 09:32 AM
Last Post: buran
  code with no tuple gets : IndexError: tuple index out of range Aggam 4 3,024 Nov-04-2020, 11:26 AM
Last Post: Aggam
  [split] Python beginner: Weird Syntax Error mnsaathvika 1 2,238 Jul-22-2019, 06:14 AM
Last Post: buran
  Code syntax with underscore and assigning to a tuple santoshbwn 1 2,040 Jun-24-2019, 12:05 PM
Last Post: ThomasL
  How to get first line of a tuple and the third item in its tuple. Need Help, Anybody? SukhmeetSingh 5 3,411 May-21-2019, 11:39 AM
Last Post: avorane
  Python beginner: Weird Syntax Error mentoly 5 10,544 Oct-13-2017, 08:06 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

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