-1

I am very very new in Python and I am trying to create a new list out of two lists when I add the two. But I get an error message which I don't really understand why (see below). I cannot use sum or numpy because it is an assignement.

For addition I wrote:

x=[24,54,84]
y=[2]

def addition(x,y):
    a=len(x)
    for i in range(a):
    x[i]=x[i]+y
    return x[i]

print(addition(x,y))  

the error message I get is:

  x[i]=x[i]+y
    ^
IndentationError: expected an indented block
Vee
  • 9
  • 1
  • Have you imported the `math` module? –  May 08 '22 at 17:38
  • 2
    It is not clear what you're trying to accomplish. Could you provide your desired output? – Robin Thibaut May 08 '22 at 17:40
  • 1
    You're missing a tab for the line of code after `for` – user107511 May 08 '22 at 17:42
  • Welcome to Stack Overflow! Please take the [tour]. What's your question exactly? What are you trying to accomplish? Please read [ask]. You can [edit] to clarify. If you're looking for debugging help, you need to add your expected output and actual output -- or if you get an error, the [full error message with traceback](https://meta.stackoverflow.com/q/359146/4518341). Just saying "it doesn't work" is not descriptive enough; it's not clear if you're getting an `IndentationError` or if the output is not what you wanted. (Reference: [mre].) – wjandrea May 08 '22 at 17:49
  • Note that your code doesn't create a new list, it looks like it modifies `x`. – wjandrea May 08 '22 at 17:50

1 Answers1

0
x=[24,54,84]
y=[2]

def addition(x,y):
    for i in range(len(x)):
        x[i]=x[i]+y[0]
    return x

print(addition(x,y)) 

Two thing where wrong:

  1. Indent in the for item to loop (need to be spaced out to be in the for)

  2. return ends the function, so return the vector instead once the loop is over

  3. i made the correction as similar as I can to your code. This code rewrites x, so instead define another variable and return that variable if is what you want.

Things i changed:

  1. a is not necessary, can be put in the for the len itself

  2. i made the suposition that y is like a constant, you have defined it like a vector so i need to take the first item of the vector in each loop

EDIT: Here's the same code without modifing x, meaning you have a new vector in the addition function as you asked

x=[24,54,84]
y=[2]

def addition(x,y):
  temp = x.copy()
  for i in range(len(x)):
    temp[i] =x[i]+y[0]
  return temp

print(addition(x,y)) 
print(x)
print(y)
Blackhole
  • 426
  • 3
  • 14
  • OP did say they're "trying to create a new list", not modify the existing one. If you do decide to modify the existing one, [it's better to not return it as well](/a/16641831/4518341). – wjandrea May 08 '22 at 18:18
  • True, you can put print(x) directly without returning, but i tried to be as close as possible with op code – Blackhole May 08 '22 at 18:23