NumPy: Convert a list and tuple into arrays
List/Tuple to Arrays
Write a NumPy program to 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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics