TypeError: can only concatenate list (not "int") to list in python
Asked Answered
V

5

14

I tried to run this code, but it showed an error:

def shoot(aliens):
    s=[0]*1000
    s[0]=0
    s[1]=1
    num=len(aliens)
    b=[[0 for m in range(1000)] for n in range(1000)]
    for j in xrange(2,num):
        for i in xrange(0,j):                
            b[j][i]=s[i]+min(int(aliens[j]),f[j-i]) ##Error here
        s[j]=max(b)

and the error:

Traceback (most recent call last):
File "module1.py", line 67, in <module>
print shoot(line)
File "module1.py", line 26, in shoot
b[j][i]=s[i]+min(int(aliens[j]),f[j-i])
TypeError: can only concatenate list (not "int") to list

please help!

Edit: added more code. s, aliens and f are other arrays. I tried to save the result to the 2 dimentional array, but it showed that error.

Vorous answered 19/7, 2013 at 20:46 Comment(3)
what are s, f and aliens?Addressee
can you please explain what your trying to get at the end ?Vinasse
well, this is a dynamic programming algorithm of shooting the maximum aliens coming to the base.Vorous
S
10
s[j] = max(b)

doesn't treat b as a 2-d array of integers and pick the biggest one. b is a list of lists. max(b) compares the lists and returns the one that compares highest. (List comparison is done by comparing the elements lexicographically.)

You want

s[j] = max(max(sublist) for sublist in b)
Surgeon answered 19/7, 2013 at 21:5 Comment(1)
oh. it seems to be another error if it goes through that error above. thank you to pointing it out.Vorous
W
1

try:

b=[[0 for m in range(1000)] for n in range(1000)]
    for j in xrange(2,num):
        for i in xrange(0,j):
             b[j][i] = s[j][i] + min(int(aliens[j]),f[j-i])

It seems to me likes is a 2D list (list of a list), and thus, you can't perform the operation.

s[j] + min(int(aliens[j]),f[j-i])
Weak answered 19/7, 2013 at 20:58 Comment(4)
it is working, but is there any other way to do that because I do not want to change 1D array to 2D array.Vorous
s is not a list of lists.Surgeon
@user2357112, if it is not a list of list, what is it then?Weak
s=[0]*1000 initializes s to a list of ints. The bugged s[j]=max(b) sets s[2] to a list, and then the error comes when the program tries to add s[2] to something.Surgeon
E
1

I got the same error with the following python code:

retList = []
for anItem in aList:
   if anItem % 2 == 0:
       retList = retList + anItem
return retList

when I changed the "+" which I used for concatenation to an append statement:

retList = []
for anItem in aList:
    if anItem % 2 == 0:
        retList.append(anItem) 
return retList

it worked fine.

Etoile answered 26/2, 2015 at 11:22 Comment(1)
Just a small caveat.. This code will only work if anItem is not a list type since + operand is more equivalent to list.extend() than list.append(). That is to say, when anItem is [3] but not 3, the result will be different.Ibadan
F
0

I had this error in a function as a conflict of a filled global vs. unused local variable: by mistake, I added something to a numerical local variable that was not known in the function, but known as a global variable of type string.

Cutting it down to a small and reproducible example:

def test():
    for j in range(2):
        print(j)
        print(i + 1) # error here, string type + 1!!
    return

i = ['a']
test()

which will output:

<ipython-input-281-10d295524223> in test()
      2     for j in range(2):
      3         print(j)
----> 4         print(i + 1)
      5     return
      6 

TypeError: can only concatenate list (not "int") to list

The global variable i is the string 'a'. You cannot add + 1 to a string.

Right function would be, of course:

def test():
    for i in range(2):
        print(i + 1)
    return
Filum answered 2/10, 2021 at 21:51 Comment(0)
R
0

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]
Respect answered 20/8, 2024 at 4:29 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.