-1

I am trying to understand how the 5th line is structured.

def removeElement(nums, val):
    start, end = 0, len(nums) - 1
    while start <= end:
        if nums[start] == val:
            nums[start], nums[end], end = nums[end], nums[start], end - 1
        else:
            start +=1
    return nums
mkrieger1
  • 19,194
  • 5
  • 54
  • 65

3 Answers3

1

It's a simple assignment of three variables

In python, you can write these three lines in one line. So here's a simple value exchange between two variable, usually you would write something like below

value1 = 1 // let
value2 = 2 // let

temp = value1
value1 = value2
value2 = temp

now you can

value1,value2 = value2,value1

That's it

Sifat Amin
  • 1,091
  • 6
  • 15
0

That's not a list comprehension, that is just python's tuple packing and unpacking at work. Essentially, it simultaneously runs these three lines:

nums[start] = nums[end]
nums[end] = nums[start]
end = end - 1

If these were run in sequence, the first two lines would conflict with each other and cause nums[start] and nums[end] to take on the original value of nums[end]. This code allows the two values to be swapped.

vikarjramun
  • 1,042
  • 12
  • 30
0

So you traverse the list and once you get to the value, which is now at index start. Then you swap the last value with this new value and that's basically what the function does. But again, this is not list comprehension and if you want to remove an element just use del l[index] or use remove

Marta
  • 99
  • 8