Is it possible to assign to a list slice in one go, that would achieve the following as:
mylist = [1,2,3,4,5,6,7]
xs = mylist[:-1]
x = mylist[-1]
xs == [1,2,3,4,5,6]
x == 7
I know I can write it like this:
xs,x = mylist[:-1], mylist[-1]
but I was wondering if it is possible to this any other way. Or have been spoilt by Haskell's pattern matching.
something like x,xs = mylist[:funky:slice:method:]
You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.
Using the slice function to create a slice object can be useful if we want to save a specific slice object and use it multiple times. We can do so by first instantiating a slice object and assigning it to a variable, and then using that variable within square brackets.
Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.
You can in Python 3:
>>> *xs, x = [1, 2, 3, 4, 5, 6, 7]
>>> xs
[1, 2, 3, 4, 5, 6]
>>> x
7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With