Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a list from another

Tags:

list

kotlin

Let say I have some values in a List. I would like to return another list with a new element

fun newList():List<Int>{    
    val values =listOf<Int>(1,2,3,4,5,6);
    return 7::values; // something like that
}
like image 972
Nicolas Zozol Avatar asked Apr 22 '17 21:04

Nicolas Zozol


People also ask

How do you create a list from a different list in Python?

Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 seconds to complete.

What is one way to create a list from another sequence in Python?

We have three methods to add new elements to a list: append , insert , and extend . An empty list is created. The append method adds an item at the end of the list; we append two strings. The insert method places an element at a specific position indicated by the index number.

Can we create a list inside another list?

The items in the outer list are List<int> objects. In the first line, you create the outer list. In the second line, you create a list of int and add it as one of the items in the outer list. In the third line, you add an integer to the first inner list in the outer list.


2 Answers

The Kotlin lists have the plus operator overloaded in kotlin-stdlib, so you can add an item to a list:

val values = listOf(1, 2, 3, 4, 5, 6)
return values + 7

There's also an overload that adds another list:

val values = listOf(1, 2, 3, 4, 5, 6)
return listOf(-1, 0) + values + listOf(7, 8)

Note that in both cases a new list is created, and the elements are copied into it.

For MutableList<T> (which has mutating functions, in contrast with List<T>), there is a plusAssign operator implementation, that can be used as follows:

fun newList(): List<Int> {    
    val values = mutableListOf(1, 2, 3, 4, 5, 6)
    values += 7
    values += listOf(8, 9)
    return values
}
like image 152
hotkey Avatar answered Oct 26 '22 14:10

hotkey


A different approach by using spread operator. Maybe in some case would be simpler than using + sign or mutableListOf

fun newList(): List<Int>{
    val values = listOf(1,2,3,4,5,6)
    return listOf(7, *values.toTypedArray(), 8, 9)
}
like image 34
Gary LO Avatar answered Oct 26 '22 13:10

Gary LO