Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
m0nk3yz
Mar 13, 2002

Behold the power of cheese!

Scaevolus posted:

I thought the Global Interpreter Lock made this form of threading pointless? Or are you doing multiple processes?

You can use parallel python (http://www.parallelpython.com/) or pyprocessing (http://pyprocessing.berlios.de/) to easily side-step the GIL. My particular favorite is the latter (pyprocessing). In fact I am working on a pep and with python-dev to see if I can get pyprocessing into the stdlib for 2.6. The pyprocessing module is a drop-in replacement for the threading module (it's API compliant)

Adbot
ADBOT LOVES YOU

Scaevolus
Apr 16, 2007

m0nk3yz posted:

You can use parallel python (http://www.parallelpython.com/) or pyprocessing (http://pyprocessing.berlios.de/) to easily side-step the GIL. My particular favorite is the latter (pyprocessing). In fact I am working on a pep and with python-dev to see if I can get pyprocessing into the stdlib for 2.6. The pyprocessing module is a drop-in replacement for the threading module (it's API compliant)

quote:

Internally ppsmp uses processes and IPC (Inter Process Communications) to organize parallel computations. All the details and complexity of the latter are completely taken care of, and your application just submits jobs and retrieves their results (the easiest way to write parallel applications).

Thanks, I didn't know about this.

Bozart
Oct 28, 2006

Give me the finger.

tripwire posted:

This isn't strictly a python question, but its related so I figured I'd ask here. I've been tweaking and fiddling with a genetic algorithm in python for a while, and Ive had some success using parallel python to break up the population that needs to be evaluated so it each required evaluation can be farmed out to an available processor.

This works fine because each member of the population that needs evaluating shouldn't have any effect on the evaluations for other members; their evaluation is objective, and generally is in the form of a positive float.

I've been scratching my head on how I can adapt this new variation on the algorithm:
Instead of receiving an objective score, the first individual is characterized by its behavior during evaluation (in this case, just an x,y coordinate pair), and that behavior is added to an archive of behaviours for the run. Each future evaluation is compared to the nearest 15 neighbors in the archive or within the current population and only added if it is higher than some dynamically set threshold.

IS it impossible to do this in parallel?

I'm not exactly a python expert, but it seems to me you should just save all of the individuals scores and then filter them afterwards. The filtering is not easily parallizable from what I can think of.

tripwire
Nov 19, 2004

        ghost flow

Bozart posted:

I'm not exactly a python expert, but it seems to me you should just save all of the individuals scores and then filter them afterwards. The filtering is not easily parallizable from what I can think of.

It's a little bit more tricky than that because of the change from a generational dynamic to a steady-state one (I was in essence doing what you are suggesting already, it works fine when you have large populations which are cleanly divisible by the number of processors you have). The search dynamic is apparently damaged if you don't use a population which changes only one individual at a time, probabilistically, versus the old system where the population is replaced by a new one every generation. That's why I've changed my software to replace one individual per step, and hence evaluation, which is how a steady state genetic algorithm should work I think. Since its done serially like this, I'm really puzzled how you would share work between different computers.

Sock on a Fish
Jul 17, 2004

What if that thing I said?
I'm trying to decide between Django and TurboGears for a web app. One thing that I definitely don't like about Django is that updating my model requires manually generating and running SQL queries. I've looked at evolution, but I'm scared to use something that's not yet stable in my application.

However, I don't know if the ORM that TurboGears uses suffers from the same problem. I don't find any warnings about it in the TurboGears or SQLObject documentation, but I wanted to ask to be sure. Can I update a model in TurboGears and expect to see those changes in the database?

Nickopops
Jan 8, 2006
You must be this funky to ride.
Can someone point me to a guide or something somewhere on organising a small project into modules? This is the first thing I've written in Python, and I just have no idea how to organise my classes and functions into separate modules. Whatever I try I just end up getting errors because each module doesn't have access to what it needs. Maybe I'm just organising everything wrong. Either way, is there a decent guide somewhere on general project organisation in Python?

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

Nickopops posted:

Can someone point me to a guide or something somewhere on organising a small project into modules? This is the first thing I've written in Python, and I just have no idea how to organise my classes and functions into separate modules. Whatever I try I just end up getting errors because each module doesn't have access to what it needs. Maybe I'm just organising everything wrong. Either way, is there a decent guide somewhere on general project organisation in Python?
Brush up on modules, namespaces, and packages here, it is not a problem with organization.
http://docs.python.org/tut/node8.html

No Safe Word
Feb 26, 2005

Sock on a Fish posted:

I'm trying to decide between Django and TurboGears for a web app. One thing that I definitely don't like about Django is that updating my model requires manually generating and running SQL queries. I've looked at evolution, but I'm scared to use something that's not yet stable in my application.

However, I don't know if the ORM that TurboGears uses suffers from the same problem. I don't find any warnings about it in the TurboGears or SQLObject documentation, but I wanted to ask to be sure. Can I update a model in TurboGears and expect to see those changes in the database?

There's a whole Django thread actually, and I answered a similar question in it, which basically boils down to having django generate a sql dump script with your data in it, recreating the model (drop/recreate), and then re-inserting the data after you've modified the dump appropriately.

If you use SQLite (which is awesome), it unfortunately doesn't support removal of columns from schema anyway, so you'd have to drop the table :(

Bozart
Oct 28, 2006

Give me the finger.

tripwire posted:

It's a little bit more tricky than that because of the change from a generational dynamic to a steady-state one (I was in essence doing what you are suggesting already, it works fine when you have large populations which are cleanly divisible by the number of processors you have). The search dynamic is apparently damaged if you don't use a population which changes only one individual at a time, probabilistically, versus the old system where the population is replaced by a new one every generation. That's why I've changed my software to replace one individual per step, and hence evaluation, which is how a steady state genetic algorithm should work I think. Since its done serially like this, I'm really puzzled how you would share work between different computers.

This sort of stuff is really interesting to me and is why I am in the process of learning python - could you tell me what resources you use to implement this, and what information is out there as well?

king_kilr
May 25, 2007

No Safe Word posted:

There's a whole Django thread actually, and I answered a similar question in it, which basically boils down to having django generate a sql dump script with your data in it, recreating the model (drop/recreate), and then re-inserting the data after you've modified the dump appropriately.

If you use SQLite (which is awesome), it unfortunately doesn't support removal of columns from schema anyway, so you'd have to drop the table :(

Or you can use a 3rd party project such as django-evolution(which works pretty drat well IMO).

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.
I am using sqlalchemy(with sqlite) in a project and I have having issues my objects/database becoming useless eventually after multiple shut downs and restarts. The application I am developing this for does not emit any type of shutdown signal so I can not save on that event so I am looking for suggestion on how I can reduce the chances that corruption or an incomplete write might occur?

Ideally I would like the application to emit a signal so I can cleanly deal with the database but that is out of my hands for various reasons.

For some background it is a rss reader database/backend that uses feedparser to handle feeds. It is being used by another project which is where this particular issue is occurring.

hey mom its 420
May 12, 2007

Check out http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html where it says "Transactions". I think that might be what you're looking for.

SmirkingJack
Nov 27, 2002


I remember that when this one came out I was beginning to visit Python and it inspired a little project. I did not have the time to follow through on it but things have been getting a little monotonous for me lately and I needed to take a break and do something different.

So I finally got around to writing this. It grabs xkcd's RSS feed and looks for an update. If it finds one then it will download the new strip to a pictures directory and set it as the wallpaper. I was going to make it cross platform but I ended up not feeling like it and hey, it was only supposed to be a small break. So sorry, OS X only.

Download the script to wherever you want and save this plist to ~/Library/LaunchAgents and change the path appropriately. The plist has the script running every three hours so if you want it to be different then change TimeInterval to however many seconds.

Perhaps in 2011, when I hope to have some more free time, I will update it to work with other operating systems (not hard) and other comics.

A couple caveats - Prior to running this the background preferences must be set to a centered non-rotating picture. And it might freak out if ~/Pictures/xkcd doesn't already exist, I can't remember.

Somebody fucked around with this message at 05:10 on May 28, 2008

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
I'm working on a metaclass that builds a lot of repetitious code from a class attribute. No problems there. But I also want it to generate some automatic documentation for the class and the class's __init__. It seems wasteful and error prone to do this repetious documentation by hand.

Unfortunately __doc__ is immutable. There seem to be a number of messy ways around this.

This is for a hobby library and I'm trying to simplify it for people who want to extend the library as well as people who just want to use code by them or me.

What I want to know is if there's a 'proper' way to deal with this, or at least a clean way. I'd rather stick to the standard library.

I can post the code if necessary, but it's a dirty sketch as I play around with possible designs, filled with numerous stanzas irrelevant to the discussion, and I basically just want to know how to use a metaclsass to alter docstrings.

Allie
Jan 17, 2004

Lord Uffenham posted:

Unfortunately __doc__ is immutable. There seem to be a number of messy ways around this.

Have you tried using __new__?

code:
>>> class MetaFoo(type):
...     def __new__(cls, name, bases, dct):
...         dct['__doc__'] = 'foo'
...         return type.__new__(cls, name, bases, dct)
... 
>>> class Foo(object):
...     __metaclass__ = MetaFoo
... 
>>> Foo.__doc__
'foo'

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
I'm sorry. I was unclear. I am using __new__, the problems is updating the docstring of the __init__ method of the class being created. Note that I'm using attrs where Milde used dct and that the gross assumptions my code makes about how the class's __init__ method operated are valid in context, and that I've tried to cutaway code and comments that don't apply to the questions at hand.

code:
        #if they don't define an __init__ we have to so we can tag it with docs
        def __init__(self, **file_info):
            self.__dict__.update(formatted_dict)

        #see if they have an init otherwise use ours
        init = getattr(attrs, '__init__', __init__)
        #grab its docstring or the empty string
        idoc = getattr(init, '__doc__', '')
        #append our generated documentation
        idoc += '\n' + init_docstrings

        #FIXME won't let me write to this, need a way around this
        setattr(init, '__doc__', idoc)

        setattr(attrs, '__init__', init)

Allie
Jan 17, 2004

Set cls.__init__.im_func.__doc__. You're trying to assign a doc string to the instance method, which is just a wrapper around the function.

Lonely Wolf
Jan 20, 2003

Will hawk false idols for heaps and heaps of dough.
Awesome! Thanks for the help. Where in the documentation would I find more about these abstrusely named properties?

Allie
Jan 17, 2004

It's not a pretty doc, but this page lists most of this kind of info: http://docs.python.org/ref/types.html. That same manual also has information on special methods.

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
The processing PEP is now live (draft form): http://www.python.org/dev/peps/pep-0371/

ATLbeer
Sep 26, 2004
Über nerd
Python GUI's?

Any opinions?

Tkinter, Wx, GTK, QT?

Which one has better IDE support currently? Are there any good IDE's?

Anyone in particular I should avoid if I'm using OS X?

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
Choose Wx or Qt:

Tkinter is completely obsolete and ugly.

Wx is a wrapper around Gtk on Linux, and around the native UI on other platforms, so I'd choose it over Gtk for portability.

I like Qt myself, but I don't have any killer arguments for why it's better than Wx.

joeyjojo
Jul 3, 2004
Has anyone ever compiled the sqlite3 library (new in 2.5) for Mac OS9 python (the latest version of which I can find is 2.3)?

I have seen a few posts after googling which seem to suggest some kind of implementation is possible but not found any how tos or help as to how to do it.

So any help would be much appreciated or even a no not possible if anyone knows the answer.

Thanks.

ashgromnies
Jun 19, 2004
I'm writing some image manipulation stuff in Python using PIL and was wondering if anyone would review a few basic functions I wrote(I'm a Python n00b).

code:
def getHue(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	if dom == dim:
		return 0
	elif dom == 'r':
		return ((60 * (pixel['g'] - pixel['b'])/(pixel.get(dom) - pixel.get(dim))) % 360
	elif dom == 'g':
		return 60 * (pixel['b'] - pixel['r'])/(pixel.get(dom) - pixel.get(dim)) + 120
	else: # max is b
		return 60 * (pixel['r'] - pixel['g'])/(pixel.get(dom) - pixel.get(dim)) + 240
		
def getLight(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = 0.5 * (maxi + mini)
	return light

def getSat(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = getLight(pixel)
	if dom == dim:
		return 0
	elif light <= 0.5:
		return (maxi - mini)/(2 * light)
	elif light > 0.5:
		return (maxi - mini)/(2 - 2 * light)
		
rgbscale = lambda rgb: {'r': (rgb['r'] / 255), 'g': (rgb['g'] / 255), 'b': (rgb['b'] / 255)}
rgb2hsl = lambda rgb: {'h': getHue(rgb), 's': getSat(rgb), 'l': getLight(rgb)}
Basically what I have here is rgbscale, which converts a ([0:255], [0:255], [0:255]) RGB value to ([0:1], [0:1], [0:1]) and rgb2hsl which converts a ([0:1], [0:1], [0:1]) RGB value to a Hue,Saturation,Lightness value.

Anyone have comments on my style or where I'm not being "Pythonish"?

edit: I just realized it makes NO SENSE AT ALL to return a 3-tuple for HSL from a function that expects a dict for RGB. Ergh.

editx2: changed that

ashgromnies fucked around with this message at 22:02 on May 28, 2008

Id4ever
Dec 2, 2004

ATLbeer posted:

Python GUI's?

Any opinions?

Tkinter, Wx, GTK, QT?

Which one has better IDE support currently? Are there any good IDE's?


I can't give an opinion on the others, but I recently started using PyQt and so far I'm loving it. I find it to be very flexible and powerful while still being incredible easy to use. It comes with a good GUI designer, though personally I prefer to do the GUI layout in code. Documentation is pretty good as it's mostly based on Trolltech's excellent Qt docs. I would however also recommend the book Rapid GUI Programming with Python and Qt if you've never used Qt before.

As for IDEs, I like Eclipse/PyDev, and Trolltech also ships a Qt integration module so you can do the GUI design from within Eclipse. There's also the Eric4 IDE, which is actually made using PyQt. I haven't used it much myself, though.

No Safe Word
Feb 26, 2005

ashgromnies posted:

I'm writing some image manipulation stuff in Python using PIL and was wondering if anyone would review a few basic functions I wrote(I'm a Python n00b).

code:
def getHue(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	if dom == dim:
		return 0
	elif dom == 'r':
		return ((60 * (pixel['g'] - pixel['b'])/(pixel.get(dom) - pixel.get(dim))) % 360
	elif dom == 'g':
		return 60 * (pixel['b'] - pixel['r'])/(pixel.get(dom) - pixel.get(dim)) + 120
	else: # max is b
		return 60 * (pixel['r'] - pixel['g'])/(pixel.get(dom) - pixel.get(dim)) + 240
		
def getLight(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = 0.5 * (maxi + mini)
	return light

def getSat(pixel):
	dom = max(pixel, key=lambda a: pixel.get(a))
	dim = min(pixel, key=lambda a: pixel.get(a))
	maxi = pixel.get(dom)
	mini = pixel.get(dim)
	light = getLight(pixel)
	if dom == dim:
		return 0
	elif light <= 0.5:
		return (maxi - mini)/(2 * light)
	elif light > 0.5:
		return (maxi - mini)/(2 - 2 * light)
		
rgbscale = lambda rgb: {'r': (rgb['r'] / 255), 'g': (rgb['g'] / 255), 'b': (rgb['b'] / 255)}
rgb2hsl = lambda rgb: {'h': getHue(rgb), 's': getSat(rgb), 'l': getLight(rgb)}
Basically what I have here is rgbscale, which converts a ([0:255], [0:255], [0:255]) RGB value to ([0:1], [0:1], [0:1]) and rgb2hsl which converts a ([0:1], [0:1], [0:1]) RGB value to a Hue,Saturation,Lightness value.

Anyone have comments on my style or where I'm not being "Pythonish"?

edit: I just realized it makes NO SENSE AT ALL to return a 3-tuple for HSL from a function that expects a dict for RGB. Ergh.

editx2: changed that
Honestly, I'd think the tuple is better. A little less descriptive perhaps, but those 3-tuples are pretty standard within that space (ie, you're basically never going to pass color information as anything other than RGB(A), and HSL is also the standard ordering).

And I think using lambdas on the last bit is a little too "clever", just write the small function that actually does it:
code:
def rgbscale(rgb):
    return {'r': rgb['r'] / 255,
            'g': rgb['g'] / 255,
            'b': rgb['b'] / 255}

def rgb2hsl(rgb):
    return {'h': getHue(rgb),
            's': getSat(rgb),
            'l': getLight(rgb)}
Or convert those to use tuples if appropriate:
code:
def rgbscale(rgb):
    return (rgb[0]/255, rgb[1]/255, rgb[2]/255)

def rgb2hsl(rgb):
    return (getHue(rgb), getSat(rgb), getLight(rgb))

tehk
Mar 10, 2006

[-4] Flaw: Heart Broken - Tehk is extremely lonely. The Gay Empire's ultimate weapon finds it hard to have time for love.

ATLbeer posted:

Python GUI's?

Any opinions?

Tkinter, Wx, GTK, QT?

Which one has better IDE support currently? Are there any good IDE's?

Anyone in particular I should avoid if I'm using OS X?

QT4.4 for OS X, Windows, and Linux. It has a decent API and works great as a cross platform toolkit, but it is GPL rather than LGPL so keep that in mind. I have not used WX much yet but it was nice when I did. I prefer pyGTK when developing for X11 systems because I know the API and it works well with Glade3svn+WingIDE. Avoid GTK+ on OSX unless you do not mind having an X server running or using the experimental native GTK+.

Hopefully someone adds better python support to Monodevelop because I am really enjoying their code completion tool and deeply integrated Stetic UI designer that does WinForms and GTK(C# grr).

tehk fucked around with this message at 23:13 on May 28, 2008

hey mom its 420
May 12, 2007

Hey m0nk3yz, congratz on the PEP, I read it and it looks real good, I hope it gets accepted!

deimos
Nov 30, 2006

Forget it man this bat is whack, it's got poobrain!
I just realized I've been reading m0nk3yz's blog for a while if that's his PEP.

BlackDiamonds
Mar 15, 2007
Have any python programmers (new or old) have used Ulipad ? Some one just posted a link to a screen cast on the Tutor mailing list, which shows off several of the features on it.

It just used it and I think it will be a really good replacement for Notepad++, and a really handy tool for Python development because of how lightweight it is, the code completion, "notes feature", debugger and the built in python shell.

tripwire
Nov 19, 2004

        ghost flow

Bozart posted:

This sort of stuff is really interesting to me and is why I am in the process of learning python - could you tell me what resources you use to implement this, and what information is out there as well?

I'm modifying the source of neat-python, which is a pretty decent implementation of NEAT to use.
One of the benefits of python that I'm really enjoying is how understandable the code is; if you want to learn about how neuroevolution works I'd recommend studying neat-python code over any of the c++ or even java implementations, which had a lot more code devoted to just making things work, or work fast. A lot of people will bitch and moan that python isn't suitable for number crunching but really that is misleading I think.

All of the CPU intensive parts of this code can be sped up by using psyco and special optimized c++ libraries for manipulating neural nets, but because I'm using this 32-bit simulation environment and my native python is incompatible (64-bit), I have to use the python packaged with the simulator, version 2.3. Because this interpreter is incompatible with my installed modules, I've simply been throwing my modified neat-python folder into the simulation directory and waiting for the simulator developer to hurry up and throw python 2.5 in there.

Right now I've pretty much mangled the code in my attempts to implement a steady state algorithm novelty search (first time using python, it's been a real learning experience), but once I'm satisfied thats its cleaned up enough to be legible and understandable (and once it works properly) I'll ask the dev to throw it on the SVN. Which is here by the way: http://code.google.com/p/neat-python/source/browse

m0nk3yz
Mar 13, 2002

Behold the power of cheese!

deimos posted:

I just realized I've been reading m0nk3yz's blog for a while if that's his PEP.

It is, and I hope it's been a decent read, although I've been heads down with the new job/PEP/python magazine work lately.

politicorific
Sep 15, 2007
here's an easy one hopefully.
let's say I have a bunch of different strings stored in class "Shop"
so that Shop.a = "string", Shop.b = "strang", Shop.c = "streng", ect...

now I want to remove a number of characters from those strings and replace them. First I try writing a function:
code:
def remove(x):
    x=x.split('i')  #'i' represents a unicode string
    x=''.join(x)
    return x
but if I run remove(Shop.a) it doesn't store the output to Shop.a, x is treated as a local variable.

Am I doing this wrong? Should I define this function within the "Shop" class?

The next thing that's bothering me, I don't want to have to write
code:
 remove(Shop.a)
remove(Shop.b)
remove(Shop.c)
remove(Shop.d)
...
can I define a list and then use a "for" command save my wrists?

Habnabit
Dec 30, 2007

lift your skinny fists like
antennas in germany.

politicorific posted:

here's an easy one hopefully.
let's say I have a bunch of different strings stored in class "Shop"
so that Shop.a = "string", Shop.b = "strang", Shop.c = "streng", ect...

now I want to remove a number of characters from those strings and replace them. First I try writing a function:
code:
def remove(x):
    x=x.split('i')  #'i' represents a unicode string
    x=''.join(x)
    return x
but if I run remove(Shop.a) it doesn't store the output to Shop.a, x is treated as a local variable.

Am I doing this wrong? Should I define this function within the "Shop" class?
Yes, you are. Strings are immutable, so if you try to modify it like that, nothing will happen. You have to explicitly reassign the new value to the old name, so Shop.a = remove(Shop.a) would work.

politicorific posted:

The next thing that's bothering me, I don't want to have to write
code:
 remove(Shop.a)
remove(Shop.b)
remove(Shop.c)
remove(Shop.d)
...
can I define a list and then use a "for" command save my wrists?

Not easily, and not cleanly. The best way would be to store the strings in a different data structure, like a dictionary.

ATLbeer
Sep 26, 2004
Über nerd

politicorific posted:

here's an easy one hopefully.
let's say I have a bunch of different strings stored in class "Shop"
so that Shop.a = "string", Shop.b = "strang", Shop.c = "streng", ect...

now I want to remove a number of characters from those strings and replace them. First I try writing a function:
code:
def remove(x):
    x=x.split('i')  #'i' represents a unicode string
    x=''.join(x)
    return x
but if I run remove(Shop.a) it doesn't store the output to Shop.a, x is treated as a local variable.

Am I doing this wrong? Should I define this function within the "Shop" class?

The next thing that's bothering me, I don't want to have to write
code:
 remove(Shop.a)
remove(Shop.b)
remove(Shop.c)
remove(Shop.d)
...
can I define a list and then use a "for" command save my wrists?
As mentioned above your data structure isn't quite right for this type of application

I'm just typing this out and not double checking my code so there maybe a syntax error or two in here so YMMV

code:
def remove(x):
    x = x.split('i')
    x = "".join(x)
    return x
Shops = []
Shops.append('string')
Shops.append('strung')
Shops.append('lokiee')

temp = []
for a_shop in Shops:
    temp.append(remove(a_shop))

Shops = temp

ashgromnies
Jun 19, 2004
What's the specific reason that arrays are faster than tuples?

When should you use an array versus a tuple? From what I understand, you should use a tuple when you want to form it and pass it off without manipulating its internals any further - that is, "I have calculated three pieces of data and want to return them from a function. I should use a tuple."

But why use a tuple over an array in that case?

For example:

code:
tuple = ()
for i in range(1000000):
    tuple += (i,)
runs slower than

code:
array = []
for i in range(1000000):
    array.append(i)
but if I did

code:
def some_method:
    value1 = some_calculation1()
    value2 = some_calculation2()
    value3 = some_calculation3()
    return (value1,value2,value3)
why is it better than

code:
def some_method:
    value1 = some_calculation1()
    value2 = some_calculation2()
    value3 = some_calculation3()
    return [value1,value2,value3]

ashgromnies fucked around with this message at 05:05 on May 30, 2008

Allie
Jan 17, 2004

Those are lists, not arrays (an array is a specialized data type in Python). You use tuples when you want to return or hold on to multiple values. They're like structs in C, but without named elements.

Lists on the other hand are mutable, unlike tuples. They're meant for being grown and shrunk, filtered, sorted, etc. When you append to a list, it doesn't create a new list. You can't append to tuples, only make new tuples.

king_kilr
May 25, 2007
Tuples are immutable, use them as such.

No Safe Word
Feb 26, 2005

Tuples are for collections of heterogeneous types, lists are for collections of homogeneous types.

edit: Quote from GvR

No Safe Word fucked around with this message at 06:49 on May 30, 2008

Adbot
ADBOT LOVES YOU

m0nk3yz
Mar 13, 2002

Behold the power of cheese!
And because tuples are immutable, they can be used as dictionary keys!

  • Locked thread