Lists in Python Lists as ArgumentsParameters Lists as

  • Slides: 6
Download presentation
Lists in Python Lists as Arguments/Parameters

Lists in Python Lists as Arguments/Parameters

Lists as arguments to functions • Just like other data types, lists can be

Lists as arguments to functions • Just like other data types, lists can be sent to functions as arguments • The function must be aware of the fact that a parameter is a list, so it can treat it as a list (use subscripts) • Lists are passed to functions in a different way than other arguments you have seen so far

Passed by value • The process y ou have seen so far is that

Passed by value • The process y ou have seen so far is that the values of arguments are copied into the spaces reserved for parameters • The function can do anything you want with the copies • The copies are deleted when the function finishes and returns • This is called ‘passing arguments by value’

Passing by reference • Lists are handled differently • Their address is sent to

Passing by reference • Lists are handled differently • Their address is sent to the function in the place of a parameter • Using the address (also called the reference) the function can change the elements of the list – in other words, the function is changing the original contents of the original list • In other words, the list contents can be changed permanently

Python versus other languages • In languages like C, C++ and Java, passing by

Python versus other languages • In languages like C, C++ and Java, passing by reference is fairly common • A main reason for this is that those languages can return no more than one value via a return statement • If a function needs to return two things, it must use pass by reference to get one of the things back to the calling code

Python vs. other languages • Python on the other hand can return many different

Python vs. other languages • Python on the other hand can return many different values through the return statement • Typically functions do not need to pass things by reference because of this fact • The main thing to be aware of is that a function can change a list, which will affect the calling function’s variable. Most Python programmers would consider doing this a mistake by the programmer. • If you do use passing by reference, document it WELL in the header, so that anyone using the function knows that a list argument can be changed!