Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning two variables to one list slice

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:]

like image 878
beoliver Avatar asked Jun 16 '12 14:06

beoliver


People also ask

Can I assign 2 variables at once?

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.

Can you use variable in Slice Python?

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.

How do you assign multiple variables in Python?

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.


1 Answers

You can in Python 3:

>>> *xs, x = [1, 2, 3, 4, 5, 6, 7]
>>> xs
[1, 2, 3, 4, 5, 6]
>>> x
7
like image 135
senderle Avatar answered Oct 10 '22 20:10

senderle