Reputation:
I am currently working with two lists, and I wanted to know what was the best way to pop the last element from one list and add it to the end of another list in Scala? I can't find the pop equivalent of Python in Scala so I'm a little confused.
For example:
list1: List1[Int] = List(4,5,6)
list2: List2[Int] = List(5,7,8)
From there I want to add the last element of List 2 to List1, and return
list3: List1[Int] = List(4,5,6,8)
list4: List2[Int] = List(5,7)
Upvotes: 1
Views: 829
Reputation: 2686
You don't need to use mutable list you can do that by using simple operations like last and drop.
val list1 = List(4,5,6)
val list2= List(5,7,8)
what you can do is:
//val lastElem = list1.last // can cause an error if list is empty
can use takeRight instead
val lastElem = list1.takeRight(1)
print(list1 :+ lastElem, list2.drop(1)) // output, List(4,5,6,8), List(5, 7)
You can also save these values into new val
val appenedList = list1:+lastElem
val popedList = list2.drop(1)
Upvotes: 1
Reputation: 27356
It is easy to compute list4
using init
, but list3
needs care because list2
might be empty. This is a safe way to do it:
list3 = list1 ++ list2.takeRight(1)
list4 = list2.init
Upvotes: 2
Reputation: 1303
Since you want to manipulate the list, you can use mutable
collections of Scala, which is highly not recommended. But just to give a flavour of it, this how you can do it:
val list1 = mutable.ListBuffer(4,5,6)
val list2 = mutable.ListBuffer(5,7,8)
val dropped = list2.remove(list2.size - 1)
println(list2)
list1.append(dropped) // OR you can use =>
// list1 += dropped
println(list1)
Update: Here are few options for without making List
mutable
. Now you can either make new lists out of it like newList1
and newList2
or make them variable var
.
Disclaimer: having
var
s in your Scala code is a big NO, unless you are really sure about why you are doing it.
Here is the sample (similar to the above) code for both approaches:
newList1
and newList2
val list1 = List(4,5,6) val list2 = List(5,7,8) val (newList2, dropped) = list2.splitAt(list2.size - 1) val newList1 = list1 ++ dropped println(newList2) println(newList1)
var
s var list1 = List(4,5,6) var list2 = List(5,7,8) val result = list2.splitAt(list2.size - 1) val dropped = result._2 list2 = result._1 list1 = list1 ++ dropped println(list2) println(list1)
Upvotes: 1
Reputation: 3055
You can simply use init
(which is opposite of tail
) and last
(which is opposite of head
) method of scala list
.
val list1 = List(1,2,3)
val list2 = List(4,5,6)
val newList1 = list1 ++ List(list2.last) // return 1,2,3,6
val newList2 = list2.init // return 4,5
Upvotes: 0
Reputation: 641
If you can change you approach to use immutable list, you can achieve it by
val list1 = List(4,5,6)
val list2 = List(5,7,8)
val list3 = list1 :+ list2.last
val list4 = list2.dropRight(1)
println(list3, list4)
output
(List(4, 5, 6, 8),List(5, 7))
Upvotes: 1