Learn Python in 10 minutes
Shameless plug: If you want a free online financial management app, you could do me a favor and visit www.moneygement.com, see if it’s to your liking. Thanks.
Preliminary fluff
So, you want to learn the Python programming language but can’t find a concise and yet full-featured tutorial. This tutorial will attempt to teach you Python in 10 minutes. It’s probably not so much a tutorial as it is a cross between a tutorial and a cheatsheet, so it will just show you some basic concepts to start you off. Obviously, if you want to really learn a language you need to program in it for a while. I will assume that you are already familiar with programming and will, therefore, skip most of the non-language-specific stuff. The important keywords will be highlighted so you can easily spot them. Also, pay attention because, due to the terseness of this tutorial, some things will be introduced directly in code and only briefly commented on.
Properties
Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don’t have to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented (i.e. everything is an object).
Getting help
Help in Python is always available right in the interpreter. If you want to know how an object works, all you have to do is call help(<object>)! Also useful are dir(), which shows you all the object’s methods, and <object>.doc, which shows you its documentation string:
Help on int object:
(etc etc)
>>> dir(5)
['__abs__', '__add__', ...]
>>> abs.__doc__
'abs(number) -> number\n\nReturn the absolute value of the argument.'
Syntax
Python has no mandatory statement termination characters and blocks are specified by indentation. Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon (:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-line comments. Values are assigned (in fact, objects are bound to names) with the equals sign (”=”), and equality testing is done using two equals signs (”
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar
Data types
The data structures available in python are lists, tuples and dictionaries. Sets are available in the sets library (but are built-in in Python 2.5 and later). Lists are like one-dimensional arrays (but you can also have lists of other lists), dictionaries are associative arrays (a.k.a. hash tables) and tuples are immutable one-dimensional arrays (Python “arrays” can be of any type, so you can mix e.g. integers, strings, etc in lists/dictionaries/tuples). The index of the first item in all array types is 0. Negative numbers count from the end towards the beginning, -1 is the last item. Variables can point to functions. The usage is as follows:
>>> mylist = ["List item 1", 2, 3.14]
>>> mylist[0] = "List item 1 again"
>>> mylist[-1] = 3.14
>>> mydict = {"Key 1": "Value 1", 2: 3, "pi": 3.14}
>>> mydict["pi"] = 3.15
>>> mytuple = (1, 2, 3)
>>> myfunction = len
>>> print myfunction(mylist)
3
You can access array ranges using a colon (:). Leaving the start index empty assumes the first item, leaving the end index assumes the last item. Negative indexes count from the last item backwards (thus -1 is the last item) like so:
>>> print mylist[:]
['List item 1', 2, 3.1400000000000001]
>>> print mylist[0:2]
['List item 1', 2]
>>> print mylist[-3:-1]
['List item 1', 2]
>>> print mylist[1:]
[2, 3.14]
Strings
Its strings can use either single or double quotation marks, and you can have quotation marks of one kind inside a string that uses the other kind (i.e. “He said ‘hello’.” is valid). Multiline strings are enclosed in triple double (or single) quotes (”“”). Python supports Unicode out of the box, using the syntax u“This is a unicode string”. To fill a string with values, you use the % (modulo) operator and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use dictionary substitutions, like so:
Name: Poromenos
Number: 3
String: ---
strString = """This is
a multiline
string."""
# WARNING: Watch out for the trailing s in "%(key)s".
>>> print "This %(verb)s a %(noun)s." % {"noun": "test", "verb": "is"}
This is a test.
Flow control statements
Flow control statements are if, for, and while. There is no select; instead, use if. Use for to enumerate through members of a list. To obtain a list of numbers, use range(<number>). These statements’ syntax is thus:
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
# Check if number is one of
# the numbers in the tuple.
if number in (3, 4, 7, 9):
# "Break" terminates a for without
# executing the "else" clause.
break
else:
# "Continue" starts the next iteration
# of the loop. It's rather useless here,
# as it's the last statement of the loop.
continue
else:
# The "else" clause is optional and is
# executed only if the loop didn't "break".
pass # Do nothing
if rangelist[1] == 2:
print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
print "The second item (lists are 0-based) is 3"
else:
print "Dunno"
while rangelist[1] == 1:
pass
Functions
Functions are declared with the “def” keyword. Optional arguments are set in the function declaration after the mandatory arguments by being assigned a default value. For named arguments, the name of the argument is assigned a value. Functions can return a tuple (and using tuple unpacking you can effectively return multiple values). Lambda functions are ad hoc functions that are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) cannot be changed. This is because only the memory location of the item is passed, and binding another object to a variable discards the old one, so immutable types are replaced. For example:
functionvar = lambda x: x + 1
>>> print functionvar(1)
2
# an_int and a_string are optional, they have default values
# if one is not passed (2 and "A default string", respectively).
def passing_example(a_list, an_int=2, a_string="A default string"):
a_list.append("A new item")
an_int = 4
return a_list, an_int, a_string
>>> my_list = [1, 2, 3]
>>> my_int = 10
>>> print passing_example(my_list, my_int)
([1, 2, 3, 'A new item'], 4, "A default string")
>>> my_list
[1, 2, 3, 'A new item']
>>> my_int
10
Classes
Python supports a limited form of multiple inheritance in classes. Private variables and methods can be declared (by convention, this is not enforced by the language) by adding at least two leading underscores and at most one trailing one (e.g. “__spam”). We can also bind arbitrary names to class instances. An example follows:
common = 10
def __init__(self):
self.myvariable = 3
def myfunction(self, arg1, arg2):
return self.myvariable
# This is the class instantiation
>>> classinstance = MyClass()
>>> classinstance.myfunction(1, 2)
3
# This variable is shared by all classes.
>>> classinstance2 = MyClass()
>>> classinstance.common
10
>>> classinstance2.common
10
# Note how we use the class name
# instead of the instance.
>>> MyClass.common = 30
>>> classinstance.common
30
>>> classinstance2.common
30
# This will not update the variable on the class,
# instead it will bind a new object to the old
# variable name.
>>> classinstance.common = 10
>>> classinstance.common
10
>>> classinstance2.common
30
>>> MyClass.common = 50
# This has not changed, because "common" is
# now an instance variable.
>>> classinstance.common
10
>>> classinstance2.common
50
# This class inherits from MyClass. Multiple
# inheritance is declared as:
# class OtherClass(MyClass1, MyClass2, MyClassN)
class OtherClass(MyClass):
# The "self" argument is passed automatically
# and refers to the class instance, so you can set
# instance variables as above, but from inside the class.
def __init__(self, arg1):
self.myvariable = 3
print arg1
>>> classinstance = OtherClass("hello")
hello
>>> classinstance.myfunction(1, 2)
3
# This class doesn't have a .test member, but
# we can add one to the instance anyway. Note
# that this will only be a member of classinstance.
>>> classinstance.test = 10
>>> classinstance.test
10
Exceptions
Exceptions in Python are handled with try-except [exceptionname] blocks:
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
else:
# Exception didn't occur, we're good.
pass
finally:
# This is executed after the code block is run
# and all exceptions have been handled, even
# if a new exception is raised while handling.
print "We're done with that."
>>> some_function()
Oops, invalid.
We're done with that.
Importing
External libraries are used with the import [libname] keyword. You can also use from [libname] import [funcname] for individual functions. Here is an example:
from time import clock
randomint = random.randint(1, 100)
>>> print randomint
64
File I/O
Python has a wide array of libraries built in. As an example, here is how serializing (converting data structures to strings using the pickle library) with file I/O is used:
mylist = ["This", "is", 4, 13327]
# Open the file C:\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = file(r"C:\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
myfile = file(r"C:\text.txt", "w")
myfile.write("This is a sample string")
myfile.close()
myfile = file(r"C:\text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
# Open the file for reading.
myfile = file(r"C:\binary.dat")
loadedlist = pickle.load(myfile)
myfile.close()
>>> print loadedlist
['This', 'is', 4, 13327]
Miscellaneous
- Conditions can be chained.
1 < a < 3checks that a is both less than 3 and more than 1. - You can use
delto delete variables or items in arrays.
- List comprehensions provide a powerful way to create and manipulate lists. They consist of an expression followed by a
forclause followed by zero or moreiforforclauses, like so:
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.
# Check how many items have this property.
>>> sum(1 for i in [3, 3, 4, 4, 3] if i == 4)
2
>>> del lst1[0]
>>> print lst1
[2, 3]
>>> del lst1
- Global variables are declared outside of functions and can be read without any special declarations, but if you want to write to them you must declare them at the beginning of the function with the “global” keyword, otherwise Python will bind that object to a new local variable (be careful of that, it’s a small catch that can get you if you don’t know it). For example:
def myfunc():
# This will print 5.
print number
def anotherfunc():
# This raises an exception because the variable has not
# been bound before printing. Python knows that it an
# object will be bound to it later and creates a new, local
# object instead of accessing the global one.
print number
number = 3
def yetanotherfunc():
global number
# This will correctly change the global.
number = 3
Epilogue
This tutorial is not meant to be an exhaustive list of all (or even a subset) of Python. Python has a vast array of libraries and much much more functionality which you will have to discover through other means, such as the excellent book Dive into Python. I hope I have made your transition in Python easier. Please leave comments if you believe there is something that could be improved or added or if there is anything else you would like to see (classes, error handling, anything).

This work is licensed under a
Creative Commons Attribution-Share Alike 3.0 License.
Python is not "weakly typed". It is strongly, dynamically, implicitly typed.
"Equality testing", not "truth testing", is done with the == sign. The == operator tells you if its arguments are equal, not if they are true.
Dictionaries are not "one-dimensional named arrays". They are associative arrays, sometimes known as hash tables, although "hash table" is really the name of one implementation of associative arrays.
A useful use of the array range colon is to copy an array:
newary = oldary[:]
Multiline strings can be enclosed in '''triple single quotes''' as well as """triple double quotes""".
"Flow control statements are while, if@, and @for" contains unnecessary @ signs.
Functions returning a tuple is not the same as functions returning multiple values. You're thinking of tuple unpacking of a returned tuple, which is indeed useful ... but multiple values are something different. (Languages which support that include Common Lisp.) Multiple values has been proposed for Python, but never implemented.
Arguments are not passed "by value". They are passed "by reference". If arguments were passed by value, a function passed an array as an argument would not be able to modify it and have that modification affect the calling context, e.g.:
>>> def foo(ary):
... ary.append("yermom")
...
>>> a = ["monkey"]
>>> foo(a)
>>> a
['monkey', 'yermom']
- reply
Submitted by Fubar Obfusco (not verified) on Thu, 12/01/2006 - 08:47.I have corrected the errors you posted. Let's take it from the top.
Indeed it is strongly typed, I mistook weakly for implicitly. Equality testing indeed, wrong word. Associative arrays, named arrays,hash tables, I have seen all names, I have changed it to associative since that is the most widely used.
I am leaving your array copy example since it's better if it's in comments. I've changed the quotes as well, the @ thing was Textile screwing up.
Correct for functions returning a tuple as well, changed. Arguments are also passed by reference (the official tutorial said that arguments are passed using call by value where value is an object reference).
Thank you very much for these corrections. If you have anything else to propose please feel free to comment here.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Thu, 12/01/2006 - 14:57.It looks like your site is built on Drupal, which is PHP software. Did you look at Plone, a CMS written in Python?
- reply
Submitted by Andy (not verified) on Thu, 12/01/2006 - 20:39.My previous host didn't support Python, and this one supports it as a CGI module. I just tried Drupal and stuck with it, although Plone is great as well.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Thu, 12/01/2006 - 22:17.I think named arrays is a bad name - it only makes sense if the key type is string. An "associative array" is the more general name, and is more suitable for python since the python {} construct does allow use of any equatable, hashable and immutable type as a key.
- reply
Submitted by Anonymous (not verified) on Fri, 19/12/2008 - 19:08.What do you mean by "strongly" vs "weakly" typed? I understand that python is dynamically, implicitly typed, but not sure what the strength v. weakness is about.
Wikipedia on the subject: http://en.wikipedia.org/wiki/Strongly_typed
- reply
Submitted by kylog (not verified) on Thu, 12/01/2006 - 20:38.Weakly typed languages don't care that much about types, i.e. you can assign strings to integers without converting, a la VBscript. Conversion is done internally. In Python you can't assign a string to an integer without doing int("123"), so 3 + "123" is illegal.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Thu, 12/01/2006 - 22:19.I'm not a Python programmer, however, I found this in Bruce Eckel's "Thinking in Python" online book:
Python is a weakly-typed language, which means it puts the minimum possible requirements on typing. For example, you could pass and return different types from the same function.
#: c01:differentReturns.py
def differentReturns(arg):
if arg == 1:
return "one"
if arg == "one":
return 1
print differentReturns(1)
print differentReturns("one")
#:~
- reply
Submitted by Anonymous (not verified) on Tue, 29/08/2006 - 12:09.All that example shows is the Python is dynamically typed.
The basic story is:
*Static/dynamic refers to the type of variables (and functions): in statically-typed languages, once a variable contains a string, it can never return an int.
*Weak/strong refers to the type of objects: in weakly-typed languages, "1"+1 is allowed (although Java, which is strongly typed, DOES give special allowance for automatic casting to string).
- reply
Submitted by Max Rabkin (not verified) on Wed, 21/02/2007 - 09:03."I spent a few weeks... trying to sort out the terminology of "strongly typed," "statically typed," "safe," etc., and found it amazingly difficult.... The usage of these terms is so various as to render them almost useless."
From: http://en.wikipedia.org/wiki/Strongly_typed
This seems like an example of people using this term in a way so as to make it useless. The whole point of being strongly typed is to prevent potential runtime errors by detecting problems at compile/parse time. When you can't predict what the legitimate parameters or outputs of a function are, then you'd better give up and accept that you aren't strongly typed for any useful understanding of that term.
My main (only) real problem with Python is semantic white space. It means that a piece of code can "look right" but not "be right", especially if you've copied the snippet from another source file or forum (or it was written by someone else in general). It's just an unfortunate feature given the prevalence of very useful forums these days. Parentheses, for all their religious war issues, are more robust and convey information less ambiguously. You can automatically set indentation from parentheses if it floats you boat.
- reply
Submitted by Anonymous (not verified) on Thu, 12/07/2007 - 14:45.No, I don't think you understand. You're talking about "Static typing" but you are using the phrase "Strong typing" to describe it. Static typing is about determining type errors at compile-time, because a variable or function can only hold or return a single, explicit type. A variable or function is defined as an "int", and it can only ever hold an int or return an int. If you try to put a string into that variable, you will get a compile error. Python is not static-typed, it is dynamic-typed.
Strong typing has nothing to do with static/dynamic typing. Strong typing involves how strict conversions between types are. In a strongly typed language, like Python, you cannot simply do:
var = 123
sys.stdout.write(var)
Because you will get an error. sys.stdout.write expects a string. Even though WE know the integer 123 can easily be converted into the string "123" without losing it's meaning, Python will not do this for you automatically, because it is strongly typed. If you gave a weakly typed language the same code, it would happily convert it into "123" and print that to the screen.
- reply
Submitted by Cecil (not verified) on Thu, 12/07/2007 - 16:49.You are right: one can't pass variables containing integers to functions expecting strings and so on. But there is a confusing point in the tutorial when, few lines after declaring that Python is strongly typed, we can see how it is possible to swap 2 variables containing integer and string respectively.
Later, in this discussion about strength of Python's typing, Poromenos says "In Python you can't assign a string to an integer without doing int("123"), so 3 + "123" is illegal." The example after the comma is right but the statement is at odds with the variable swapping example.
I understood where is the trick thanks to another discussion in this same web-page, about (im)mutability of objects: when you swap those variables, what you actually are doing is creating 2 new variables with the same names as before but with exchanged types. They are not really swapping the value, they are eclipsing previous variables.
I think dynamic creation of variables (without declaration) is much more serious an issue than semantic white-space, which one can solve with a good editor (which is a good thing to have anyway).
Poromenos: I think you can make an example of multiple assignment without mixing things up with eclipsing vars. / changing types and so on. It kept me frowning in wonder for 10 minutes. :-)
Thanks for the tutorial, btw.
- reply
Submitted by Juanma (not verified) on Mon, 10/12/2007 - 22:58.You are correct, that is what happens, new variables are created. I will clarify the tutorial, thanks for the suggestion!
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Tue, 11/12/2007 - 09:19."because a variable or function can only hold or return a single, explicit type. A variable or function is defined as an "int", and it can only ever hold an int or return an int."
More precisely, this is only true when are talking about monomorphic languages (C), but false if your language supports parametric polymorphism (like ML)
- fun id x = x ;
val id = fn : 'a -> 'a
- id 5 ;
val it = 5 : int
- id "five" ;
val it = "five" : string
informally, static typing is about compile-time type checking.
len can be applied to
- reply
Submitted by Anonymous (not verified) on Fri, 28/11/2008 - 14:08.Minor correction to the correction: most variables are passed by reference. Scalar variables, e.g. integers and strings, are passed by value as in most other languages.
>>> def foo(bar):
... bar += 3
...
>>> baz = 5
>>> foo(baz)
>>> print baz
5
- reply
Submitted by Anonymous (not verified) on Thu, 12/01/2006 - 21:00.Duly changed, thanks :).
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Thu, 12/01/2006 - 22:20.Acually no, they're passed by reference as well (strings passed by value, what IS that ???). Oh and string is not a scalar type.
- reply
Submitted by Anonymous (not verified) on Sat, 04/02/2006 - 20:18.Well, the example works as posted, so integers aren't passed by reference... I'm confused...
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Sat, 04/02/2006 - 22:47.Passing is always by reference. Python has a concept of mutable vs immutable datatypes. List is mutable, tuple is not. int, float, bool, string are immutable too. You can not modify a immutable object.
a = 5 # a is pointing to immutable object int(5)
a = a + 1 # a is not pointing to a immutable object object int(6)
Callee passes 5 by reference, function gets the location of object int(5), but the function pointed the local variable a to a new location, int(6), and callee was not notified. Hope it clears up things.
- reply
Submitted by Amit Upadhyay (not verified) on Fri, 10/03/2006 - 23:27.It does somewhat, but by "callee" you mean "caller"? I will also update the tutorial with the new info now.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Sat, 11/03/2006 - 00:03.You are right, I meant caller, and in some other place i mentioned "not", when I meant "now".
- reply
Submitted by Amit Upadhyay (not verified) on Sat, 11/03/2006 - 09:45.Oh hmm, that complicates things :) So how does it work exactly? Does modifying immutable objects change the reference to the new object or not?
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Sat, 11/03/2006 - 11:48.You can not modify immutable objects, that's what "immutable" means. 8-) E.g., if you concatenate two strings together, a new string is allocated. But lists, dictionaries, sets and objects are mutable.
def test(a_list):
a_list.append("some value")
my_list = []
test(my_list)
my_listis now["some value"]. On the other hand you can use only immutable objects as keys for dictionaries, e.g. tuples or frozensets.To answer your question: no, the reference is never changed. But the object that is referenced can be changed if it is mutable.
- reply
Submitted by Anselm (not verified) on Thu, 12/07/2007 - 15:18.Good article!
The easiest way to prove the 'mutability' is by a data type's identity before and after the work:
E.g 1: Immutable - int
>>> i = 0; print type(i), id(i), i
6329520 0
>>> i += 1; print type(i), id(i), i
6329496 1
(Observe how the identity has changed for the immutable data type)
E.g 2: Mutable - list
>>> l = []; print type(l), id(l), l
46934625640888 []
>>> l.append(0); print type(l), id(l), l
46934625640888 [0]
(Observe how the identity remains the same for the mutable data type)
Just my 2 Aussie cents.
- reply
Submitted by Anonymous (not verified) on Sat, 21/07/2007 - 03:57.> Arguments are not passed "by value". They are passed "by reference".
Actually, arguments are just values pointing to objects, and alas, that's not "Pure ByVal" or "Pure ByRef". The most appropriate way to say it is that arguments are passed thru "object reference".
Quoting from GvR Python Tutorial: "arguments are passed using call by value (where the value is always an object reference, not the value of the object) [....] Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee makes to it (items inserted into a list)."
- reply
Submitted by JPVilla (not verified) on Fri, 13/01/2006 - 05:02.Arguments in python are passed by value, BUT that value is a reference. If it would be passed by reference, given the following code
>>> def func(arg):... arg = ['another value']
...
>>> value = ['original value']
>>> func(value)
A
>>> print valueshould display - guess -
['another value'].It gives
['original value'], though.So, there is no pass-by-reference in Python. Never.
Try equivalent code in C++ and the reference-operator, then you'll see that pass-by-reference indeed yields
['another value'].Using some function on the object-argument (which changes the object's state like
appenddoes) does not show whether the mechanism used is -by-reference or -by-value.- reply
Submitted by Mr. Gung (not verified) on Fri, 13/01/2006 - 17:12.Indeed, I have tested it for myself now and it's passed by value. I have corrected it now, thanks for the help. :)
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Fri, 13/01/2006 - 20:37.I allways liked the term "pass by assignment" best: Think of each function argument as being assigned (with the python assignment semantics) on entry. So, arrays and strings get assigned object references, integers get assigned values.
- reply
Submitted by Daren Thomas (not verified) on Wed, 16/08/2006 - 09:48.Your function is wrong, it is not changing the object pointed to by arg, it is assigning "arg" to a new object, leaving original unchanged.
Try this:
>>> l = ["original value"]
>>> def func(arg):
... arg.append("value added by func")
...
>>> print l
['original value']
>>> func(l)
>>> print l
['original value', 'value added by func']
>>>
- reply
Submitted by Amit Upadhyay (not verified) on Sat, 11/03/2006 - 09:51.His function wasn't wrong, he was just trying to show that Python doesn't pass by reference. If it did pass by reference, the = operator in func *would* change l.
- reply
Submitted by Brock (not verified) on Fri, 08/12/2006 - 00:01.Bull crap. Java passes by reference and the value wouldn't change if you were using Java.
- reply
Submitted by Anonymous (not verified) on Thu, 12/07/2007 - 20:38.Not really. Objects are passed by reference, but the 'built-in' types are passed by value (various number types, boolean).
- reply
Submitted by Anonymous (not verified) on Fri, 13/07/2007 - 08:30.This is not true, Java _always_ passes by value. But if the parameter is an Object, you are passing the address of the Object (i.e. the reference) by value (you certainly don't copy the entire object onto the stack). Thus you are passing a reference by value.
Therefore, if you send the object a message (e.g. call a method on the Object) that changes its state, then this is observable outside the method body. But if you assign to the parameter within the method, you do not affect the caller's reference (it will still point to the same Object). And it sounds like Python works the same way.
- reply
Submitted by Sean (not verified) on Tue, 21/08/2007 - 09:28.Java never passes by reference. Java always passes by value. In Java, the value of an Object variable is a reference. The reference is passed by value.
I'm pretty sure Python is like Java in this sense. Everything is pass by value but many values are references.
- reply
Submitted by Anonymous (not verified) on Thu, 09/10/2008 - 16:23.well I think there is some mix up here, object references are values, that is the variables are like normal primitive types so when u pass the reference in a function the reference is passed by value, but remember its pointing to an object. so if you assign the pointer(reference variable) that was passed by value to another object it simple cuts the link to the original object that it pointed to. So when u leave that function and get to the parent scope the old pointer is still pointing to the original object and when u display it, it gives the original but if you use the pointer and call the pointed objects method, it will modify it, so I believe python like java the objects are still passed by reference and the reference are actually passed by value. dont get it mixed up, correct me if I am wrong
- reply
Submitted by mambenanje (not verified) on Mon, 18/06/2007 - 22:13.This is similar to what the poster above has said about "pass by assignment". Python does pass the reference to the object as a value. If you change the object (for mutable types), it gets changed, if you assign to it (for immutable types) it only changes the reference in the callee.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Mon, 18/06/2007 - 23:11.I just wanted to say 'thank u' for this great and quick tutorial.
It really helped me!
- reply
Submitted by Kansloos (not verified) on Sun, 27/05/2007 - 18:48.I r glad :)
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Sun, 27/05/2007 - 19:04.I know this is an old thread, but about "by reference" vs. "by value".
arguments are passed by value, but the value that's passed in an instance of an object.
def foo(ary):
... ary.append("yermom")
... ary = 2 // the variable named "ary" is now a number instead of a variable
a = ["monkey"]
foo(a)
a
// prints ['monkey', 'yermom'], not the number 2,
That is because the instance of the object has changed, not the value of the variable
This is a subtle difference in OO languages, especially when moving from a language where something is not an object (like arrays in PHP) to a language where something is an object (like arrays in Javascript)
- reply
Submitted by Anonymous (not verified) on Fri, 13/07/2007 - 21:42.Very true, this is how the whole thing works, but I'd rather not get into *that* much detail because this is meant to be a short tutorial and if you're going to (ab)use this, chances are you either shouldn't or you are way beyond the tutorial :)
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Sat, 14/07/2007 - 13:50."Parameters are passed by reference, but mutable types (tuples, lists, ints, strings, etc) cannot be changed. For example:"
shouldnt this be
"Parameters are passed by reference, but immutable types (tuples, ints, strings, etc) cannot be changed. For example:"
immutable, not mutable objects cannot be changed, and lists are mutable.
- reply
Submitted by Chris Lohfink (not verified) on Wed, 19/03/2008 - 19:34.You're right, I have no idea what I was doing there. Lists are obviously mutable, and the example below that doesn't include an example for this behaviour. I'll change it now, thanks.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Wed, 19/03/2008 - 21:25.It sais at the top - Python is Strongly typed... READ :D
- reply
Submitted by Anonymous (not verified) on Sun, 13/07/2008 - 14:47.you are all amateurs. python is the greatest! i spend all my evenings on it. i heart the python.
- reply
Submitted by MarkEveritt (not verified) on Thu, 31/07/2008 - 08:36.When you specify an array range, it takes elements from the start index up to (but NOT including) the end index, so your output for the [-3:-2] example is wrong. The correct result is:
lstList = ["List item 1", 2, 3.14]
>>> print lstList[-3:-2]
['List item 1']
- reply
Submitted by Bill Dimm (not verified) on Thu, 12/01/2006 - 23:18.That's odd, you're right. I tested those in the interpreter, I must have missed one. Thanks.
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Thu, 12/01/2006 - 23:55.I imagine a line segment, for example from x=0 to x=4. Think of this line segment as having five marks, x=0,x=1,x=2,x=3,x=4. and some data Z,A,B,C are lying on each subsegments of length 1. That's how I think of the list r = [Z,A,B,C].
0_Z_1_A_2_B_3_C_4
Then r[1:3] is the list of those data that are in between marks x=1 and x=3, that is [A,B].
- reply
Submitted by pianio8 (not verified) on Sun, 27/08/2006 - 22:00.Python is "object-oriented (i.e. everything is an object)." I would say it is object oriented because it supports objects, but it is also functional (because it supports functions) and procedural as well. Importantly, not everything is an object! I.e. the number 4 is not an object, it has not class, or methods.
"Comments are single line." Better to say comments are terminated by the end of line. You can have a statement followed by a comment that takes up only half of the line. (I did say these were picky comments.)
I'm not sure lists are really one dimensional arrays. An array implies that each element can be accessed in constant time, but inserting a new element is costly because you have to move all the other elements down. A subtle distinction, but important if you care about efficiency of algorithms.
You write "Python has no line termination characters" I think you mean to say "Python has no statement termination characters". But even that is not true. You can use ";" in your Python code at the end of each line (and in certain other cases), but you don't have to.
Personally, I like to use dictionay substitutions for strings. So I would add that:
print "Hello %(user_name)s your web-site %(web_site)s is awesome" % { 'user_name': 'poromenos', 'web_site': 'www.poromenos.org' };
Also, I would mention "Python: Essential Reference" as an oustanding book for experience programmars, wanting a 10hour intro to python and handy command reference.
- reply
Submitted by Stefan (not verified) on Fri, 13/01/2006 - 01:35.You are, indeed, very picky :) About the object-oriented thing, I knew someone would say it, and you're absolutely right. About lists, my focus was mainly on the fact that there are no multidimensional lists (except for scipy), but you're right again :). About comments, I meant that you have no multiline comments (that I know of, anyway :), and I didn't know the dictionary thing, I'll start using it from now on, it's much more legible and easy.
Thanks a lot :)
---
Vidi, Vici, Veni.
- reply
Submitted by Poromenos on Fri, 13/01/2006 - 01:41.it's vini vidi vinci, i saw, i came, i won.
- reply
Submitted by eyko (not verified) on Fri, 13/01/2006 - 04:10.