Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Need help understanding return statement
Hi Guys,

Am new to Python, came across a strange looking piece of code as below....

I checked and it works but I am not understanding the return statement. Can you please help.....

def v_add(v, w):
   return [v_i + w_i for v_i, w_i in zip(v, w)]
can any one please elaborate the return statement here in depth?

It's a comprehension. A list comprehension in particular.
sajley likes this post
Feel like you're not getting the answers you want? Checkout the help/rules for things like what to include/not include in a post, how to use code tags, how to ask smart questions, and more.

Pro-tip - there's an inverse correlation between the number of lines of code posted and my enthusiasm for helping with a question :)
In order to properly answer, need to see more code, specifically what the call to the function looks like,
v & w
Is it a function to add two vectors? List comprehension could be rewritten as a for loop:

def v_add(v, w):
    result = []
    for v_i, w_i in zip(v, w):
        result.append(v_i + w_i)

        # print only to show what is going on
        print("v_i = {}, w_i = {}, result = {}".format(v_i, w_i, result))
    return result
zip() is a built-in function that "zips" its argument(s), it yields tuples of i-th elemens of its arguments - for example when iterating over zip([1,2,3], [4,2,2]), it gives (1,4), (2, 2), (3, 2).  Those tuples are unpacked into v_i and w_i variables. 

Example run:
>>> v = [1, 2, 3] >>> w = [4, 2, 2] >>> v_add(v, w) v_i = 1, w_i = 4, result = [5] v_i = 2, w_i = 2, result = [5, 4] v_i = 3, w_i = 2, result = [5, 4, 5] [5, 4, 5]
snippsat, micseydel, sajley like this post
Yes Zivoni, this is addition of two Vectors.

Thanks a lot every one for your help. 

Am quite an experienced programmer but some how Python is proving tricky for me. There are too many ways of achieving an outcome in it. 
Am looking for a book which will teach Python is a very simple way..checked books such a a byte of python, python the hard way, core python etc.. but still not able to get the grip.


Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  HELP! Return Statement Debugging HappyMan 5 167 Jan-27-2020, 07:31 PM
Last Post: michael1789
  Embedding return in a print statement Tapster 3 180 Oct-07-2019, 03:10 PM
Last Post: Tapster
  return statement usage SB_J 3 299 Jul-16-2019, 07:24 PM
Last Post: snippsat
  I don't understand this return statement 357mag 4 354 Jul-10-2019, 07:02 PM
Last Post: perfringo
  Return Statement in Python IDLE editor NMW 10 3,875 Jul-11-2017, 09:47 PM
Last Post: NMW
  Python basics about __init__ and return statement wk14 5 2,391 Oct-25-2016, 04:31 PM
Last Post: micseydel

Forum Jump:

Users browsing this thread: 1 Guest(s)