w3resource

NumPy: Convert a list and tuple into arrays


List/Tuple to Arrays

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.


For more Practice: Solve these Related Problems:

  • Convert a list and a tuple to NumPy arrays and verify that their shapes match expected dimensions.
  • Create arrays from a nested list and a tuple, then perform element-wise arithmetic between them.
  • Transform a tuple of tuples into a multidimensional array and confirm the resulting shape.
  • Convert a list of mixed numeric types into an array while explicitly setting the dtype to maintain precision.

Go to:


PREV : 8x8 Checkerboard Pattern
NEXT : Append Values to Array


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.