-2

I have this code:

import numpy as np
x= list(np.arange(1,9,0.5))
d = x + 2
print(d)

However the output gave this kind of error:

can only concatenate list not "int" to list

I'm trying to convert list to int using this code:

int(list(x))

But it gave another error. Can you please help me solving this. Thank you!

Python learner
  • 1,159
  • 1
  • 8
  • 20
nobel
  • 51
  • 1
  • 8
  • What output do you want? Do you want to append 2 to the list, or add 2 to each item in the list (or something else entirely)? – DavidW Mar 14 '22 at 09:43
  • `d = x + 2` what do you mean by this ? – Ajay Mar 14 '22 at 09:45
  • Not sure what you attempting in trying to cast a list to an int, perhaps you want to cast each element to an int? – Harry Jones Mar 14 '22 at 09:47
  • I want to generate range of number from 1-9, then, each number will add to 2. Or d= x + 2. – nobel Mar 14 '22 at 09:52
  • I've marked a duplicate which does what you ask. However if you just keep the Numpy array (and don't convert it to a list) then you add to it directly – DavidW Mar 14 '22 at 10:01

2 Answers2

0

If you want to add 2 to each element, you need to use a map function like so:

d = list(map(lambda y: y + 2, x)) 
Harry Jones
  • 336
  • 3
  • 8
-1

The “TypeError: can only concatenate list (not “int”) to list” error is raised when you try to concatenate an integer to a list.

This error is raised because only lists can be concatenated to lists. To solve this error, use the append() or the '+' method to add an item to a list.

d = x + [2]
#or
x.append(2)

Here are some other ways to do it: link

EDIT:

if you want to add 2 to every value in x:

1.x = list(np.arange(1,9,0.5) + 2)

or

2.x = [i+2 for i in x]

BiRD
  • 134
  • 1
  • 8