Python Forum
Need help understanding return statement
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help understanding return statement
#4
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:
Output:
>>> 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]
Reply


Messages In This Thread
RE: Need help understanding return statement - by zivoni - Mar-02-2017, 07:29 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Common understanding of output processing with conditional statement neail 6 982 Sep-17-2023, 03:58 PM
Last Post: neail
  Need help with Return statement Columbo 13 2,464 Sep-17-2022, 04:03 PM
Last Post: Columbo
  How to invoke a function with return statement in list comprehension? maiya 4 2,964 Jul-17-2021, 04:30 PM
Last Post: maiya
  syntax error on return statement l_butler 5 3,193 May-31-2020, 02:26 PM
Last Post: pyzyx3qwerty
  return statement will not work TheTechRobo 2 2,692 Mar-30-2020, 06:22 PM
Last Post: TheTechRobo
  HELP! Return Statement Debugging HappyMan 5 3,200 Jan-27-2020, 07:31 PM
Last Post: michael1789
  Embedding return in a print statement Tapster 3 2,364 Oct-07-2019, 03:10 PM
Last Post: Tapster
  return statement usage SB_J 3 2,489 Jul-16-2019, 07:24 PM
Last Post: snippsat
  I don't understand this return statement 357mag 4 2,830 Jul-10-2019, 07:02 PM
Last Post: perfringo
  Return Statement in Python IDLE editor NMW 10 10,780 Jul-11-2017, 09:47 PM
Last Post: NMW

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020