I have a Tuple2
of List[List[String]]
and I'd like to be able to convert the tuple to a list so that I can then use List.transpose()
. Is there any way to do this? Also, I know it's a Pair
, though I'm always a fan of generic solutions.
To convert a tuple to list in Python, use the list() method. The list() is a built-in Python method that takes a tuple as an argument and returns the list. The list() takes sequence types and converts them to lists.
We can use the list() function to convert tuple to list in Python. After writing the above code, Ones you will print ” my_tuple ” then the output will appear as a “ [10, 20, 30, 40, 50] ”. Here, the list() function will convert the tuple to the list.
Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).
Works with any tuple (scala 2.8):
myTuple.productIterator.toList
Scala 2.7:
(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList
Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:
def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)
You could, of course, define similar type-safe conversions for all the Tuples (up to 22).
Using Shapeless -
@ import syntax.std.tuple._
import syntax.std.tuple._
@ (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
@ (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)
Note that type information is not lost using Shapeless's toList
.
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