Home > Net >  python 'concatenate' requires extra parentheses
python 'concatenate' requires extra parentheses

Time:03-31

I'm trying to concatenate 3 lists. When I try to use concatenate, like so, I get an error (TypeError: 'list' object cannot be interpreted as an integer):

import numpy as np

a = [1]
b = [2]
c = [3]
z = np.concatenate(a, b, c)

But if I put "extra" parentheses, it works like so:

z = np.concatenate((a, b, c))

Why?

CodePudding user response:

I am not sure what library you are using (concatenate is not a built-in python 3.x function). However, I'll explain what I think is going on.

When you call concatenate(a, b, c), the function concatenate is sent three parameters: a, b, and c. concatenate then performs some logic that is (presumably) not the desired behavior.

When you call concatenate((a, b, c)), a tuple (effectively a list that cannot be changed) is created with a value of (a, b, c), which is evaluated to ([1], [2], [3]). Then this tuple is passed to the concatenate function. The following code is actually equivalent to your second code snippet:

a = [1]
b = [2]
c = [3]
y = (a, b, c)  # This evaluates to ([1], [2], [3]).
z = concatenate(y)

I hope I've explained this clearly enough. Here's an article that explains tuples in more depth, if I haven't: https://www.w3schools.com/python/python_tuples.asp

EDIT: Thanks for including the library. Here's the code for what you're probably trying to do:

import numpy as np
a = [1]
b = [2]
c = [3]
z = np.array(a   b   c)  # Lists can be concatenated using the ` ` operator. Then, to make a numpy array, just call the constructor
  • Related