-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!

5
  • 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)? Commented Mar 14, 2022 at 9:43
  • d = x + 2 what do you mean by this ? Commented Mar 14, 2022 at 9: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? Commented Mar 14, 2022 at 9:47
  • I want to generate range of number from 1-9, then, each number will add to 2. Or d= x + 2. Commented Mar 14, 2022 at 9: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 Commented Mar 14, 2022 at 10:01

2 Answers 2

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)) 
Sign up to request clarification or add additional context in comments.

2 Comments

The output must be equal to: [3, 3.5, 4.0, 4. 5,......]. All numbers must be added to 2 >
I think I've got what you mean, updated my answer
-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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.