Michael
Michael

Reputation: 16142

Print first element in list using Scala

How can I print the first element in list using Scala?

For example in Python I can just write:

>>>l = [1,2,3,4]
>>>one = l[0]
>>>print one

How can I do that on Scala

Thanks.

Upvotes: 6

Views: 13977

Answers (4)

Branislav Lazic
Branislav Lazic

Reputation: 14826

The element can be retrieved using index-based access like this:

object ListDemo extends App {
    val lst = List(1, 2, 3)
    println(lst(0)) // Prints specific value. In this case 1.
                    // Number at 0 position.
    println(lst(1)) // Prints 2.
    println(lst(2)) // Prints 3.
}

Upvotes: 11

Viraj Wadate
Viraj Wadate

Reputation: 6203

Here we have created an object (Object name: TestList) which containing variable myList.

scala> object TestList{
     |       def main(args: (Array[String])){
     |       var myList = List(1,2,3,4,5)
     |       println("Complete List is : "+myList)
     |       println("Reverse List : "+myList.reverse)
     |       println("Print Send Element from list : " + myList(1))
     |       println("Print First three element : "+ myList.take(3))
     |       println("Remove First two element : "+myList.drop(2))
     |       }
     |       }

defined object TestList

Calling object with main Method

scala> TestList.main(Array(""))

OUTPUT:

    Complete List is : List(1, 2, 3, 4, 5)
    Reverse List : List(5, 4, 3, 2, 1)
    Print Send Element from list : 2
    Print First three element : List(1, 2, 3)
    Remove First two element : List(3, 4, 5)

Upvotes: 1

Bartosz Bilicki
Bartosz Bilicki

Reputation: 13275

Answer can easily be found in scaladoc for list

def head: A
Selects the first element of this list.

Upvotes: 2

Hiura
Hiura

Reputation: 3530

Basically, your python code is equivalent of:

scala> val l = 1 :: 2 :: 3 :: 4 :: Nil
l: List[Int] = List(1, 2, 3, 4)

scala> val one = l.head
one: Int = 1

scala> println(one)
1

(Run in the scala interpreter.)

Here is the documentation about Scala's List.


It was asked as a subsidiary question «how do I display each element?».

Here is a recursive implementation using pattern matching:

scala> def recPrint(xs: List[Int]) {
     | xs match {
     |     case Nil => // nothing else to do
     |     case head :: tail =>
     |         println(head)
     |         recPrint(tail)
     | }}
recPrint: (xs: List[Int])Unit

scala> recPrint(l)
1
2
3
4

As David Weber pointed out in the comments, if you cannot use a recursive algorithm to visit your list's elements then you should consider using another container, because accessing the i-th element of a List takes O(N).

Upvotes: 9

Related Questions