How would you pop an element from the end of a list in scala, and add it to the end of another list?

scala add element to end of list
scala remove element from list
scala list
scala add to list in loop
scala listbuffer
scala mutable list
scala remove element from list by index
scala prepend to list

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)

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

How to add elements to a List in Scala (List, ListBuffer , How to add elements to a List in Scala (List, ListBuffer) can do when working with a Scala List is to create a new List from an existing List . of a List and is also mutable — i.e., you can add and remove elements in it — the� Scala List FAQ: How do I add elements to a Scala List? This is actually a trick question, because you can't add elements to a Scala List; it's an immutable data structure, like a Java String. Prepending elements to Scala Lists. One thing you can do when working with a Scala List is to create a new List from an existing List.

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)


(List(4, 5, 6, 8),List(5, 7))

How to delete elements from a List (or ListBuffer) in Scala , A List is immutable, so you can't delete elements from it, but you can filter out the elements you don't want while you assign the result to a new� Though using :: is very common, there are additional methods that let you prepend or append single elements to a List: scala> val x = List(1) x: List[Int] = List(1) scala> val y = 0 +: x y: List[Int] = List(0, 1) scala> val y = x :+ 2 y: List[Int] = List(1, 2) You can also merge lists to create a new list. See Recipe 11.5 for examples. Discussion

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)

  list1.append(dropped) // OR you can use => 
  // list1 += dropped

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

  1. With 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

  1. With vars
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


List, This includes the index-based lookup of elements, length , append and reverse . Returns a new list containing the elements from the left hand operand followed by the elements from the right Appends all elements of this list to a string builder using start, end, and separator strings. def remove(p: (A) ⇒ Boolean): List[A]. In Scala, list is defined under scala.collection.immutable package. A list is a collection of same type elements which contains immutable data. we generally use last function to print last element of a list. Below are the examples to find the last element of a given list in Scala. Simply print last element of a list

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)

scala.collection.immutable.List, def addString (b: StringBuilder, start: String, sep: String, end: String): StringBuilder. Appends all elements of this list to a string builder using start, end, and� A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

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

Scala Standard Library 2.13.3, It provides constant time prepend and append. "Scala's Collection Library overview" section on List Buffers for more Appends all elements of this collection to a string builder using start, end, and Builds a new iterable collection by applying a partial function to all elements of this def remove(idx: Int, count: Int): Unit. Cast the receiver object to be of type T0.. Note that the success of a cast at runtime is modulo Scala's erasure semantics. Therefore the expression 1.asInstanceOf[String] will throw a ClassCastException at runtime, while the expression List(1).asInstanceOf[List[String]] will not.

Concrete Mutable Collection Classes | Collections, Additionally, array buffers can have data efficiently added to the end. A ListBuffer is like an array buffer except that it uses a linked list internally Also, on a mutable queue, the dequeue method will just remove the head element from the as there isn't already another element in the array that has the same hash code. Hi, I am trying to reverse elements of a list into another list. But somehow I am not able to populate the list or the array. This is the latest code where I tried using array to populate the list contents in reverse order and then return a list from it.

List, Any time you want to add or remove List elements, you create a new List from an existing List . Because List is immutable you can't add new elements to it. This works because a List is a singly-linked list that ends with the Nil element. Scala program that splits list, uses splitAt // This list contains four Booleans. val list = List (true, false, true, true) // Split this list at index 2 (before the third element). This returns a tuple containing two lists.

append() and extend() in Python, Append: Adds its argument as a single element to the end of a list. a string or a # another list) at the end of my_list my_list.append(object). This is Recipe 11.4, “How to Delete Elements from a List (or `ListBuffer`) in Scala” Problem. You want to delete elements from a Scala List or ListBuffer. Solution. A List is immutable, so you can’t delete elements from it, but you can filter out the elements you don’t want while you assign the result to a new variable:

  • A List is immutable. What you're asking is easy to do but the results are list3 and list4, i.e. new lists. If you want to mutate existing collections you might try Stack which has .push and .pop or Queue which has .enqueue and .dequeue.
  • ah thank you, i'll look into queue's and such!
  • If you want to try an immutable and recursive alternative, List are meant to be constructed and traversed in a head-tail fashion, so you could be taking the head of one add prepending it to another, there is even the reverse_::: method which will do that: List(3, 2, 1) reverse_:::List(4, 5, 6) === List(1, 2, 3, 4, 5, 6).
  • No-one has yet pointed out that accessing the last element of a list is O(N) in the size of the list. So a different data structure is probably the way to go. Whether Stack and Queue are appropriate depends a little on how often you will need to do this - is it just a one off or inside a key loop in your program etc.
  • its inside a loop, basically its inside a while loop and while the condition is true, i want it to take the last element from one list and remove it from that list, and then add it to another list. i've been looking at buffered lists so far and i think those might work but if you have any better implementations i'm happy to learn
  • This will fail if list2 is empty
  • Right. Your answer is more suitable. Thanks
  • we don't need mutable list actually!!
  • The true solution lies in the true context, actually. Multiple approaches updated
  • true solution lies in the true context but using mutable unnecessary is going out of functional context