Methods to Convert Python tuple or list to NumPy Array

Tuple Python

In this post, we are going to understand different Methods to Convert Python tuple or list to NumPy Array that includes N-Dimensional array,2-Dimensional array, and 1-Dimensional array from lists NumPy Array with code example.

So let us start our program examples.

#Tuple of tuples of mixed data tuples to n-Dimensional Array

In our first example we will use create a multi-dimensional array by using a tuple of tuples of mixed data types to Numpy array.

We will use numpy library to create numpy array. Let us check with example below:

import numpy as np
numtuple = ((5, 6,7,'A'), (7,9,8,'B'),(10,11,9,'C#'),(12,13,19,'D'),(14,15,18,'F'),(16,17,19,'G'))

#tuples to array

array_of_tuple = np.array(numtuple)

print('tuples to Multi-Dimensional array =\n' ,array_of_tuple)

Output:

tuples to Multi-Dimensional array =
 [['5' '6' '7' 'A']
 ['7' '9' '8' 'B']
 ['10' '11' '9' 'C#']
 ['12' '13' '19' 'D']
 ['14' '15' '18' 'F']
 ['16' '17' '19' 'G']]

# Tuple of tuples to Two Dimensional NumPy Array

In this code snippet

  • The first step is to import NumPy as np to use all methods of NumPy.
  • we are converting the Tuple of tuples to Two Dimensional Array, passing the tuple of tuples to array() method of NumPy, and printing the result. Let understand with an example

Code Example

import numpy as np

numtuple = ((5, 6), (7,9),(10,11),(12,13),(14,15),(16,17))

#tuples to array

array_of_tuple = np.array(numtuple)

print('tuples to array =\n' ,array_of_tuple) 

Output:

tuples to array =
 [[ 5  6]
 [ 7  9]
 [10 11]
 [12 13]
 [14 15]
 [16 17]]

# Tuple to one dimensional NumPy array

we are converting the Tuple to one Dimensional Array, passing the tuple to array() method of NumPy, and printing the result. Let understand with an example

Code Example

import numpy as np

numtuple = (5, 6, 7,9,10,11,12,13,14,15,16,17)

#tuple to array

array_of_tuple = np.array(numtuple)

print('tuple to array =\n' ,array_of_tuple)      

Output:

tuple to array =
 [ 5  6  7  9 10 11 12 13 14 15 16 17]

#Convert List to one dimensional NumPy array

In this code snippet,We are converting Python list to one dimensional NumPy array using asarray() method of NumPy.

import numpy as np

mylist = [5, 6, 7,9,10,11,12,13,14,15,16,17]


print('type before conversation:\n',type(mylist))
print()


#converting python list to NumPY_array
list_to_NumPY_array = np.asarray(mylist)
print('converted type:',type(mylist))
print(list_to_NumPY_array)

Output

type before conversation:
 <class 'list'>

converted type: <class 'list'>
[ 5  6  7  9 10 11 12 13 14 15 16 17]