# Python: How to create tensors with known values

In this tutorial, we are going to discuss creating tensors with known values using Python. So, at first, we are gonna know about tensors.

In different programs, we declare the variables but for working using TensorFlow we use tensors which is a multidimensional array that can contain strings, Boolean and numbers.

We can create tensors in 6 different ways: –

- By using
**constant()**function - By using
**zeros()**function - By using
**ones()**function - By using
**linspace()**function - By the use of
**range()**function - By using
**fill()**function

## Installing and Importing Tensorflow Python

Open your anaconda prompt then type: –

pip install tensorflow

This will install the latest version of TensorFlow in your machine

Now we import the TensorFlow library : –

import tensorflow as tensorflow #You can name it anything

For more on installation see: –

## Creating Tensor Using Constant() Function

This function is one of the most commonly used function to create tensors in Python it returns the value given by the user the common syntax of this function is: –

**tensorflow.constant(value, dtype, shape, name)**

where value is the array that we enter, dtype is the datatype that is default to None and is not necessary to write, shape is the shape of the tensors that we are entering it is not necessary to enter it and finally the name is the name of the tensor.

**CODE: –
**

tensor1=tensorflow.constant([1,2,3]) #create 1-D tensor with 3 integer values tensor2=tensorflow.constant(['bob','sam','john']) #create 1-D tensor with 3 string values tensor3=tensorflow.constant([[1,2,3],[4,5,6]]) #create a 2-D tensor of shape(2,3) having integer values tensor4=tensorflow.constant([1.3,2.3,4.3],tensorflow.float32,shape=[3]) #create a 1-D tensor with data type as float and shape of 3 print(tensor1) print(tensor2) print(tensor3) print(tensor4)

**Code Output: –
**

tf.Tensor([1 2 3], shape=(3,), dtype=int32) tf.Tensor([b'bob' b'sam' b'john'], shape=(3,), dtype=string) tf.Tensor( [[1 2 3] [4 5 6]], shape=(2, 3), dtype=int32) tf.Tensor([1.3 2.3 4.3], shape=(3,), dtype=float32)

## Creating Tensor Using Zeros() Function

This function returns the tensor containing all values set zero. Its common syntax is: –

*tensorflow.zeros(shape, dtype, name)*

It’s datatype by default is **float32**.

**CODE: –
**

tensor5=tensorflow.zeros([5,6]) # creates a 2-D tensor with shape of (5,6) tensor6=tensorflow.zeros([5],tensorflow.int64) # creates a 1-D tensor with shape (5,) and datatype int64 print(tensor5) print(tensor6)

**Code Output: –**

Thanks, the blog was very helpful, and also very easy to understand.