How to create a list with the same element n-times ?
Manually implementnation:
scala> def times(n: Int, s: String) =
| (for(i <- 1 to n) yield s).toList
times: (n: Int, s: String)List[String]
scala> times(3, "foo")
res4: List[String] = List(foo, foo, foo)
Is there also a built-in way to do the same ?
To repeat the elements of the list n times, we will first copy the existing list into a temporary list. After that, we will add the elements of the temporary list to the original list n times using a for loop, range() method, and the append() method.
Repeat Each Element in a List in Python using itertools. repeat() This particular problem can also be solved using python inbuilt functions of itertools library. The repeat function, as the name suggests does the task of repetition and grouping into a list is done by the from_iterable function.
Using * This is the most used method. Here we use the * operator which will create a repetition of the characters which are mentioned before the operator.
See scala.collection.generic.SeqFactory.fill(n:Int)(elem: =>A) that collection data structures, like Seq
, Stream
, Iterator
and so on, extend:
scala> List.fill(3)("foo")
res1: List[String] = List(foo, foo, foo)
WARNING It's not available in Scala 2.7.
(1 to n).map( _ => "foo" )
Works like a charm.
Using tabulate
like this,
List.tabulate(3)(_ => "foo")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With