Preferred way to create a Scala list

scala list append
scala list index
scala list of lists
scala list methods
scala create empty list
scala mutable list
scala list take
import list in scala

There are several ways to construct an immutable list in Scala (see contrived example code below). You can use a mutable ListBuffer, create a var list and modify it, use a tail recursive method, and probably others that I don't know about.

Instinctively, I use the ListBuffer, but I don't have a good reason for doing so. Is there a preferred or idiomatic method for creating a list, or are there situations that are best for one method over another?

import scala.collection.mutable.ListBuffer

// THESE are all the same as: 0 to 3 toList.
def listTestA() ={
    var list:List[Int] = Nil

    for(i <- 0 to 3) 
        list = list ::: List(i)
    list
}


def listTestB() ={
    val list = new ListBuffer[Int]()

    for (i <- 0 to 3) 
        list += i
    list.toList
}


def listTestC() ={
    def _add(l:List[Int], i:Int):List[Int] = i match {
        case 3 => l ::: List(3)
        case _ => _add(l ::: List(i), i +1)
    }
    _add(Nil, 0)
}

ListBuffer is a mutable list which has constant-time append, and constant-time conversion into a List.

List is immutable and has constant-time prepend and linear-time append.

How you construct your list depends on the algorithm you'll use the list for and the order in which you get the elements to create it.

For instance, if you get the elements in the opposite order of when they are going to be used, then you can just use a List and do prepends. Whether you'll do so with a tail-recursive function, foldLeft, or something else is not really relevant.

If you get the elements in the same order you use them, then a ListBuffer is most likely a preferable choice, if performance is critical.

But, if you are not on a critical path and the input is low enough, you can always reverse the list later, or just foldRight, or reverse the input, which is linear-time.

What you DON'T do is use a List and append to it. This will give you much worse performance than just prepending and reversing at the end.

Five ways to create a Scala List, There are many ways to create and initially populate a List : // 1 scala> val list = 1 :: 2 :: 3 :: Nil list: List[Int] = List(1, 2, 3) // 2 scala> val list = List(1� Another convenient way to create a Scala List is with the fill method: scala> val x = List.fill(3)("foo") x: List[java.lang.String] = List(foo, foo, foo) As you can see, you just specify how many items you want, and the object value you want to fill each List element with. Create a Scala List with the List class ‘tabulate’ method

And for simple cases:

val list = List(1,2,3) 

:)

Different ways to create and populate Lists in Scala, use of empty list. import scala.collection.immutable. _. // Creating object. object GFG. {. // Main method. def main(args : Array[String]). 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.

Uhmm.. these seem too complex to me. May I propose

def listTestD = (0 to 3).toList

or

def listTestE = for (i <- (0 to 3).toList) yield i

Scala Lists, Creating Uniform Lists. You can use List.fill() method creates a list consisting of zero or more copies of the same element. Try the following example program. Scala List FAQ: Can you share some Scala List class examples?. The Scala List class may be the most commonly used data structure in Scala applications. Therefore, it's very helpful to know how create lists, merge lists, select items from lists, operate on each element in a list, and so on.

You want to focus on immutability in Scala generally by eliminating any vars. Readability is still important for your fellow man so:

Try:

scala> val list = for(i <- 1 to 10) yield i
list: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

You probably don't even need to convert to a list in most cases :)

The indexed seq will have everything you need:

That is, you can now work on that IndexedSeq:

scala> list.foldLeft(0)(_+_)
res0: Int = 55

Scala - Lists, Learn what lists are and how they can be leveraged in the Scala You will create Scala List with strings , integers (both 1D & 2D) data types. "Tutorials", " Are", "The", "Best") //Head println(); println("Head of list x, y, z = " +� Scala Lists are quite similar to arrays which means, all the elements of a list have the same type but there are two important differences. First, lists are immutable, which means elements of a list cannot be changed by assignment.

I always prefer List and I use "fold/reduce" before "for comprehension". However, "for comprehension" is preferred if nested "folds" are required. Recursion is the last resort if I can not accomplish the task using "fold/reduce/for".

so for your example, I will do:

((0 to 3) :\ List[Int]())(_ :: _)

before I do:

(for (x <- 0 to 3) yield x).toList

Note: I use "foldRight(:\)" instead of "foldLeft(/:)" here because of the order of "_"s. For a version that does not throw StackOverflowException, use "foldLeft" instead.

Lists in Scala, This is how you create an initial List : You can also declare the List 's type, if you prefer, though it generally isn't necessary:. Before looking at how to sort other sequence types in Scala, it’s important to note that the preferred way to sort an Array is different than sorting the other sequential collections. If you want to sort an Array , see my other FAQ on How to sort an Array in Scala .

The List Class | Scala Book, Example: // Make a list via the companion object factory val days = List("Sunday", � Here’s a simple example showing how to use foreach to print every item in a List: scala> val x = List(1,2,3) x: List[Int] = List(1, 2, 3) scala> x.foreach { println } 1 2 3 If you’ve used a programming language like Ruby, this syntax will look familiar to you. Note that this is a relatively common way to use the foreach method.

Scala Standard Library 2.12.1, You need to create a range, list, or array of numbers, such as in a for loop, Use the to method of the Int class to create a Range with the desired elements: in many situations (such as for loops), it's generally preferable to use this syntax: Some important points about list in Scala: In a Scala list, each element must be of the same type. The implementation of lists uses mutable state internally during construction. In Scala, list is defined under scala.collection.immutable package. A List has various methods to add, prepend, max, min, etc. to enhance the usage of list. Example:

2.8. Creating a Range, List, or Array of Numbers, Our use of Scala is mainly for creating high volume services that form distributed systems This is a living document that will change to reflect our current “best practices,” but its core If your method needs a sequence, use Seq[T] , not List[T] . How to reverse a list in Scala programming. Here is step by step procedure with screenshots such as create a list sing var nums = List(4,7,2,3), reverse this list type 'nums.reverse and choose reverse: List{Int}', it is creating a new list same as giving the command.

Comments
  • What you DON'T do is use a List and append to it Is that because a new list gets created? Whereas, using a prepend operation will not create a new list?
  • @KevinMeredith Yes. Append is O(n), prepend is O(1).
  • @pgoggijr That is not true. First, there's no "change" anywhere, because it's immutable. A traversal is required because all elements have to be copied, just so a copy of the last element can be made pointing to a new element instead of Nil. Second, there's no copy of any kind on prepend: an element is created pointing to the existing list, and that's it.
  • Don't forget the cons operator! 1 :: 2 :: 3 :: Nil
  • Thanks for the answer, but the question is what do you do in the non-trivial case. I put a comment in the code explaining they were all equivalent to 0 to 3 toList.
  • Oops, sorry then! Frankly, I never use ListBuffer.
  • N.B. Vector is now also the default Seq implementation.
  • I strongly disagree; your preferred form just looks like line noise.
  • Will I? I first learned Haskell in 1999, and have been dabbling in Scala for a couple of years. I think folds are great, but if applying a fold in any given situation requires writing a cryptic string of punctuation symbols, I'd consider a different approach.
  • @Matt R: I agree. There is such a thing as overdoing it, and this is one of them.
  • @WalterChang I like the look of all those emoticons. Wait a minute, is that code? :P
  • Is it fair to call ((0 to 3) :\ List[Int]())(_ :: _) emoticode?
  • Most of the changes are in the way things are implemented internally, and in advanced things like projections. How you create a list isn't affected.
  • Ok, that's good to know. You will also get affected if you use any class in the collection.jcl package.
  • When answering a question this old (10 years), and with so many existing answers (9), it is a good practice to explain why your answer is different from all the others. As it is, it looks like you didn't understand the question.