Scala Programming: Split a given list into two lists
Scala Programming List Exercise-23 with Solution
Write a Scala program to split a given list into two lists.
Sample Solution:
Scala Code:
object Scala_List {
def split_list[A](nums: List[A], n: Int): (List[A], List[A]) = {
(nums.take(n), nums.drop(n))
}
def main(args: Array[String]): Unit = {
val nums1 = List(1,2,3,4,5,6)
println("Original List:")
println("Split the said list into 2 lists:")
println(split_list(nums1, 2))
println(split_list(nums1, 3))
}
}
Sample Output:
Original List: Split the said list into 2 lists: (List(1, 2),List(3, 4, 5, 6)) (List(1, 2, 3),List(4, 5, 6))
Scala Code Editor :
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Scala program to count the number of occurrences of each element in a given list.
Next: Write a Scala program to calculate the length of a given list.
What is the difficulty level of this exercise?
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework