w3resource

NumPy: Convert a list and tuple into arrays

NumPy: Array Object Exercise-11 with Solution

Write a NumPy program to convert a list and tuple into arrays.

NumPy: Convert a list and tuple into arrays

Sample Solution:-

NumPy Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a Python list
my_list = [1, 2, 3, 4, 5, 6, 7, 8]

# Printing a message indicating the conversion of the list to an array using np.asarray() function
print("List to array: ")

# Converting the Python list to a NumPy array using np.asarray() and printing the resulting array
print(np.asarray(my_list))

# Creating a Python tuple containing two lists
my_tuple = ([8, 4, 6], [1, 2, 3])

# Printing a message indicating the conversion of the tuple to an array using np.asarray() function
print("Tuple to array: ")

# Converting the Python tuple to a NumPy array using np.asarray() and printing the resulting array
print(np.asarray(my_tuple))

Sample Output:

List to array:                                                          
[1 2 3 4 5 6 7 8]                                                       
Tuple to array:                                                         
[[8 4 6]                                                                
 [1 2 3]]

Explanation:

In the above code –

my_list = [1, 2, 3, 4, 5, 6, 7, 8]: Defines a list called ‘my_list’ with integer values from 1 to 8. However, this line is not relevant to the final output and can be ignored.

my_tuple = ([8, 4, 6], [1, 2, 3]): Defines a tuple called ‘my_tuple’ containing two lists, each with three integer elements.

print(np.asarray(my_tuple)): Converts the nested tuple ‘my_tuple’ into a NumPy array using the np.asarray() function and prints the resulting array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to create a 8x8 matrix and fill it with a checkerboard pattern.
Next: Write a NumPy program to append values to the end of an array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-11.php