Python Forum
When do you put variables inside vs outside a function?
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
When do you put variables inside vs outside a function?
#1
Check out this code from my interpreter:
$ python3
>>> first_list = [1,2,3,4,5,6]
>>> second_list = [101,202,303,404]
>>> first_list.reverse()
>>> print(first_list)
[6, 5, 4, 3, 2, 1]
>>> reverse(second_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'reverse' is not defined
>>> 
In the first line and second lines, I define two lists. Then I proceed to reverse the order of the first_list and second_list in two different ways. The first reversal succeeds whereas the second way is rejected.

Putting the variable inside the reverse function as a parameter in the second way is how I initially would naturally use it if I were to write a script (which I can clearly see now would be rejected by the Python interpreter).

The instructor in the Udemy course I am taking suggests putting the variable in front of the function separated by a dot. I understand that the computer dictates what works and what doesn’t. I just want to know why since my (faulty) approach comes so much more naturally.

How come variables sometimes have to go in front of the function when other times it can go inside a function as a parameter?

I suppose the much more important question I now have is this: When I am manipulating variables, how do I know when to put variables outside vs inside?
Reply
#2
If first reverse works, why do you try a different format for second?

It's the same
>>> first_list = [1,2,3,4,5,6]
>>> second_list = [101,202,303,404]
>>> first_list.reverse()
>>> second_list.reverse()
>>> first_list
[6, 5, 4, 3, 2, 1]
>>> second_list
[404, 303, 202, 101]
>>>
Reply
#3
It's not as simple as inside and outside. It's the difference between using function and class method.
let's take your example. Probably you already know that everything in python is a object. In your example you have 2 lists. These are instances of a class. Every class has properties and methods. When you want to use (access) these properties and methods you will use so called dot notation. So there is method list.reverse(). Note that it will reverse the list in-place. Using dot notation you would do first_list.reverse().
Now, your example is good because there is also built-in function reversed() that will return iterator object of the reversed list. Note that usually this is not the case - i.e. there is no function to duplicate the class method.

first_list = [1,2,3,4,5,6]
second_list = [101,202,303,404]
first_list.reverse()
print(first_list)
reversed_list = list(reversed(second_list)) # because reversed returns iterator object we need the list function to make it a list
print(reversed_list)
Output:
[6, 5, 4, 3, 2, 1] [404, 303, 202, 101]
Now to the question - you will know what to do by reading the documentation for the package/module you want to use - e.g. does it provide function(s) or is it a class(es) and has some methods...
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#4
You are trying two different things.
This guy, the instructor, is just lazy.

You have two lists. These lists are not variables but objects, instances of a class in Python.
>>> first_list = [1,2,3,4,5,6]
>>> second_list = [101,202,303,404]
>>> type(first_list)
<class 'list'>
>>> type(second_list)
<class 'list'>
Well, classes are constructions which can contain variables ( instances of predefined classes in Python as integers, lists, strings, etc. ) and functions to operate with these variables.
The variables defined inside a class we call attributes of that class and the functions defined inside a class we call methods.
Each data type class in Python has its own methods. How definition of a class looks? Something simple.
>>> class Greeting:
...     def say(self): # this is a function defined inside a class definition so it's called a method of that class
...         print('Hello!')
... 
>>> greeting = Greeting() # here an instance of a class called 'greeting' is created 
When you define a variable in Python as a list, for example, it happens basically the same but the syntax is a bit different and Python is doing its things behind so you don't see it.
first_list = [1,2,3,4,5,6] # 'first_list is an instance of a class list
As I showed you at the beginning the lists are just classes in Python. Like the integers or all the other data types in Python. Everything in Python. Big Grin

So this instance of the class list has its own methods. Calling a method is different from calling a function. Let's define a simple function.
>>> def say(object):
...     print(object)
... 
Now we have a method of the class Greetings called 'say' and a function 'say'.

Calling a function is simple.
>>> say(first_list)
[1, 2, 3, 4, 5, 6]
Calling a method of a class ( or instance of a class ) is simple too. But we need to know whose class/instance is this method.
We doing it as putting the class/instance along with its method, separated by a period.
>>> greeting.say()
Hello!
As you may already guess when you reverse a list the first way ( the working one ) you just call its method 'reverse'.
So it becomes:
>>> first_list.reverse() # calling the method 'reverse' of the instance of a class list, called 'first_list'
>>> first_list
[6, 5, 4, 3, 2, 1]
In order to do the same using a function, you have to create such a function. But you didn't do that, so this function doesn't exist. And got an error.

However, there is a built-in function in Python called 'reversed'. Not 'reverse'.
>>> reversed(first_list)
<list_reverseiterator object at 0x7f7184183dd8>
It looks like it doesn't work too. We don't get the reversed list. But it works. This function returns an iterator. It says in the output what it is. An iterator from a class list called reversed and the memory address follows. The iterators are another concept in Python.
Instead of the whole list or a sequence, they return a single element. It saves memory. For the examples we are using here it doesn't matter because the lists are small. But nowadays almost nothing is small when we are talking about data.

You have to pass the iterator to a for loop for instance or to a function which knows what to do with it.
>>> list(reversed(first_list))
[6, 5, 4, 3, 2, 1]
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
@wavic, thanks for repeating my answer in so many words :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
There was no answer at all when I started to write mine. But my English practice is not enough so until I clear it from mistakes you posted yours.
I had a pause to make a coffee, eating few biscuits so... This happens Angel

One more.
You can see all methods of an object in the interpreter using the dir() function.
>>> dir(first_list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
The names of these methods will tell you what they are doing. There are some special methods we call dunder methods ( those with names like __itter__ ) but this is another topic. To see more info about the methods you can use the help function.
>>> help(first_list.reverse)
Output:
Help on built-in function reverse: reverse(...) method of builtins.list instance L.reverse() -- reverse *IN PLACE*
Press 'q' to exit the help.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#7
Thank you @buran for your concise and to the point answer. And a thousand thank-you’s go out to @wavic: I wholeheartedly appreciate the time and care you put into your answer to my question. Feedback from the both of you has helped.

I think I am beginning to understand some of this.

reverse() is a class method used to manipulate class objects such as lists. To reverse the order of a list, the variable goes “outside” (before the method separated by a dot).

To invoke the reversed() function to manipulate a declared list variable and to create the same effect, the variable goes "inside" as an argument. But to do so successfully, it’s necessary to wrap it around a list() function.

Next I’ll look into the concept of iterators in Python.

(Jun-02-2018, 05:40 AM)buran Wrote: Now to the question - you will know what to do by reading the documentation for the package/module you want to use - e.g. does it provide function(s) or is it a class(es) and has some methods...

As @wavic pointed out, to learn about what certain class methods can be used to manipulate objects and for quick reference, I can leverage dir(), type() and help() around given objects in my interpreter, right?

Obviously there are docs on Python’s official website and resources around the web also.

Thanks again you two.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  with open context inside of a recursive function billykid999 1 549 May-23-2023, 02:37 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 752 May-02-2023, 08:40 AM
Last Post: Gribouillis
  How to print variables in function? samuelbachorik 3 851 Dec-31-2022, 11:12 PM
Last Post: stevendaprano
  User-defined function to reset variables? Mark17 3 1,588 May-25-2022, 07:22 PM
Last Post: Gribouillis
  How to make global list inside function CHANKC 6 2,979 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Parameters aren't seen inside function Sancho_Pansa 8 2,814 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Do I have to pass 85 variables to function? Milfredo 10 4,185 Sep-26-2020, 10:13 PM
Last Post: Milfredo
  Creating a variables inside FOR loop zazas321 5 4,039 Sep-16-2020, 04:42 PM
Last Post: Naheed
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,417 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  Issues with storing variables outside of a function cerulean747 7 3,637 Apr-30-2020, 08:46 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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