I got the same error below:
TypeError: can only concatenate list (not "int") to list
When I tried to do addition with a list and 2
as shown below:
[2, 4, 6] + 2 # Error
So, I used tensor() of PyTorch for [2, 4, 6]
, then I could get the result as shown below:
import torch
t = torch.tensor([2, 4, 6])
t + 2 # tensor([4, 6, 8])
(t + 2).tolist() # [4, 6, 8]
torch.add(t, 2) # tensor([4, 6, 8])
torch.add(t, 2).tolist() # [4, 6, 8]
*Memos:
- tolist() can convert a tensor to a list.
- add() can do addition with 0D or more D tensors.
Or, I used array() of NumPy for [2, 4, 6]
, then I could get the result as shown below:
import numpy
arr = numpy.array([2, 4, 6])
arr + 2 # array([4, 6, 8])
(arr + 2).tolist() # [4, 6, 8]
numpy.add(arr, 2) # array([4, 6, 8])
numpy.add(arr, 2).tolist() # [4, 6, 8]
*Memos:
- tolist() can convert an array(tensor) to a list.
- add() can do addition with 0D or more D arrays(tensors).
Or, I used constant() of TensorFlow for [2, 4, 6]
, then I could get the result as shown below. *numpy().tolist()
can convert a tensor to a list:
import tensorflow as tf
t = tf.constant([2, 4, 6])
t + 2 # <tf.Tensor: shape=(3,), dtype=int32, numpy=array([4, 6, 8], dtype=int32)>
(t + 2).numpy().tolist() # [4, 6, 8]
tf.add(t, 2) # <tf.Tensor: shape=(3,), dtype=int32, numpy=array([4, 6, 8], dtype=int32)>
tf.add(t, 2).numpy().tolist() # [4, 6, 8]
*Memos:
In addition, you can do addition with lists, then you can get the results as shown below:
[2, 4, 6] + [1, 3] # [2, 4, 6, 1, 3]
[2, 4, 6] + [[1, 3], [5, 7]] # [2, 4, 6, [1, 3], [5, 7]]
And, trying to do subtraction, division, %
, ^
, &
, |
or @
with a list and 2
gets other error as shown below, then the solutions above can also solve the errors:
# ↓ Here
[2, 4, 6] <...> 2 # Error
TypeError: unsupported operand type(s) for <...>: 'list' and 'int'
But, you can do multiplication with a list and 2
as shown below. *This is element-wise multiplication:
[2, 4, 6] * 2 # [2, 4, 6, 2, 4, 6]
s
,f
andaliens
? – Addressee