# TensorFlow – How to stack a list of rank-R tensors into one rank-(R+1) tensor in parallel

Last Updated : 01 Aug, 2020

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

TensorFlow provides build in methods to  stack  a list of rank-R tensors into one rank-(R+1) tensor in parallel.

Methods Used:

• parallel_stack: This method accepts a list of Tensors and returns a Tensor with all values stacked in parallel. This methods copies pieces of the input into the output as they become available.
• stack: This method accepts a list of Tensors, axis along which values should be stacked and returns a Tensor with all values stacked.

Example 1: This example uses stack method to stack tensors.

## Python3

 # importing the library import tensorflow as tf    # Initializing the Input x = tf.constant([1, 2, 3]) y = tf.constant([4, 5, 6]) z = tf.constant([7, 8, 9])    # Printing the Input print("x: ", x) print("y: ", y) print("z: ", z)    # Stacking Tensors res = tf.stack(values =[x, y, z], axis = 0)    # Printing the resulting Tensor print("Res: ", res )

Output:

x:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
y:  tf.Tensor([4 5 6], shape=(3, ), dtype=int32)
z:  tf.Tensor([7 8 9], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[1 2 3]
[4 5 6]
[7 8 9]], shape=(3, 3), dtype=int32)

Example 2: This example uses parallel_stack method to stack the input Tensors.

## Python3

 # importing the library import tensorflow as tf    # Initializing the Input x = tf.constant([1, 2, 3]) y = tf.constant([4, 5, 6]) z = tf.constant([7, 8, 9])    # Printing the Input print("x: ", x) print("y: ", y) print("z: ", z)    # Stacking Tensors res = tf.parallel_stack(values =[x, y, z])    # Printing the resulting Tensor print("Res: ", res )

Output:

x:  tf.Tensor([1 2 3], shape=(3, ), dtype=int32)
y:  tf.Tensor([4 5 6], shape=(3, ), dtype=int32)
z:  tf.Tensor([7 8 9], shape=(3, ), dtype=int32)
Res:  tf.Tensor(
[[1 2 3]
[4 5 6]
[7 8 9]], shape=(3, 3), dtype=int32)