GIDForums  

Go Back   GIDForums > Computer Programming Forums > Python Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 16-Oct-2005, 01:02
crystalattice's Avatar
crystalattice crystalattice is offline
Flame War Instigator
 
Join Date: Apr 2004
Location: San Diego
Posts: 1,576
crystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nicecrystalattice is just really nice

A simple swap program


When you want to swap numbers in C/C++, you might write something like this:
CPP / C++ / C Code:
include <stdio.h>

void swap(int *i, int *j)
{
    int t;
    t = *i;
    *i = *j;
    *j = t;
}

void main()
{
    int a,b;
    a=5;
    b=10;
    printf("%d %d\n",a,b);
    swap(&a,&b);
    printf("%d %d\n",a,b);
}
In Python, there's an extremely easy way to swap to items; you just tell Python to do it for you:
Python Code:
>>>nudge = 1
>>>wink = ["spam", "eggs"]
>>>nudge, wink = wink, nudge   #tuples: swaps values
                               #same as T=nudge; nudge=wink; wink=T
>>>print nudge, wink
When tuples appear on both sides of an assignment operator (=), Python assigns objects on the right to targets on the left, according to their positions. This is probably easiest to understand by realizing the objects on the left don't make a tuple, they just look like it. They are simply a set of independent assignment targets. The items on the right are a tuple, which get unpacked during the assignment (the tuple provides the temporary assignment needed to achieve the swap effect).

Naturally you can use this method to swap any object types, like integers, floats, lists, etc. and you can have as many values swapped as necessary.
__________________
Start Programming with Python-A beginner's guide to programming and the Python language.
-------------
Common Sense v2.0-Striving to make the world a little bit smarter.
 
 

Recent GIDBlogPython ebook by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
[TUTORIAL] Calling an external program in C (Linux) dsmith C Programming Language 4 22-Apr-2005 14:30
Help with simple math table program (was a SIMPLE program) Bubba C Programming Language 3 09-Mar-2005 13:40
Help with a simple program. bluedragon27 C Programming Language 1 16-Nov-2004 16:40

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 09:18.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.