Never confuse education with intelligence, you can have a PhD and still be an idiot.
- Richard Feynman -

Introduction to Python

From Juneday education
Jump to: navigation, search

Some notes while learning Python

Funny thing. I decided to learn how to use pointers in Python in order to implement a swap function. Python is call-by-value so the following wouldn't work:

def swap(a, b):
    tmp = a
    a = b
    b = tmp

Since Python is call-by-value, the parameters are local variables whose values are copied on calling a function.

But there must be a library for pointers, I thought, and found ctypes:

>>> from ctypes import *
>>> def swap(a, b):
...     tmp = a[0]
...     a[0] = b[0]
...     b[0] = tmp
>>> a = c_int(1)
>>> b = c_int(2)
>>> swap(pointer(a),pointer(b))
>>> a.value
>>> b.value

That works as you can see. Then I read a little more about Python and discovered that you can also swap to variables like so:

a = 1
b = 2
a, b = b, a