TypeError: array() takes from 1 to 2 positional arguments but 9 were given in Python

Dung Do Tien Mar 26 2022 294

I have a small block code with Python basic I practiced with the array using NumPy package.
I have created an array of 2 dimensions and I want to loop and print it. Like this

 # Import the numpy library
import numpy as np

# Declaring and Initializing the one Dimension Array
snack = np.array([34,1],[34,2],[34,3],[34,4],[34,5],[34,6],[34,7],[34,8],[34,9])

# Indexing and accessing array as 2D causes IndexError
for x in snack:
  print(x[0][1])

 But when running the code above I got an error TypeError: array() takes from 1 to 2 positional arguments but 9 were given.

 Traceback (most recent call last):
  File "main.py", line 5, in <module>
    snack = np.array([34,1],[34,2],[34,3],[34,4],[34,5],[34,6],[34,7],[34,8],[34,9])
TypeError: array() takes from 1 to 2 positional arguments but 9 were given

I'm using Python 3.9.9 and running on Windows 11 64bit.

Do you have any idea for me?

Thank you so much.

Have 1 answer(s) found.
  • D

    Dan Danny Mar 26 2022

    You have got 2 mistakes

    1. You created the wrong array, please change:

     snack = np.array([34,1],[34,2],[34,3],[34,4],[34,5],[34,6],[34,7],[34,8],[34,9])

    To

     snack = np.array([[34,1],[34,2],[34,3],[34,4],[34,5],[34,6],[34,7],[34,8],[34,9]])

    2. When you loop an array 2D, each item of it is 1D so you have to change:

     print(x[0][1])

    To

     print(x[0])
    #OR
    print(x[1])

    Below is the full code for you:

     # Import the numpy library
    import numpy as np
    
    # Declaring and Initializing the one Dimension Array
    snack = np.array([[34,1],[34,2],[34,3],[34,4],[34,5],[34,6],[34,7],[34,8],[34,9]])
    
    # Indexing and accessing array as 2D causes IndexError
    for x in snack:
      print(x[1])

    #Output

     1
    2
    3
    4
    5
    6
    7
    8
    9 
Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close