Re: [Tutor] Testing for empty list
The while loop will print each index of the list. In a way it checks that if the list is empty by printing the items. As far as I know there isn't any 'True' or 'False' output from a list. If you want to do something if mylist is empty you can check it like this: if not mylist: ... do something ... T Original-Nachricht > Datum: Sun, 18 Oct 2009 20:29:53 -0500 > Von: Wayne > An: "tutor@python.org" > Betreff: [Tutor] Testing for empty list > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > > mylist = [1,2,3] > > while mylist: >print mylist.pop() > > Thanks, > Wayne > > -- > To be considered stupid and to be told so is more painful than being > called > gluttonous, mendacious, violent, lascivious, lazy, cowardly: every > weakness, > every vice, has found its defenders, its rhetoric, its ennoblement and > exaltation, but stupidity hasn’t. - Primo Levi -- Jetzt kostenlos herunterladen: Internet Explorer 8 und Mozilla Firefox 3.5 - sicherer, schneller und einfacher! http://portal.gmx.net/de/go/atbrowser ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
On Mon, Oct 19, 2009 at 3:29 AM, Wayne wrote: > Hi, I think I recall seeing this here, but I wanted to make sure I'm > correct. > Is the best way to test for an empty list just test for the truth value? > I.e. > mylist = [1,2,3] > while mylist: > print mylist.pop() Whether it is the 'best' way depends on what you mean by 'best', but I do think it's the most idiomatically pythonic one. -- André Engels, andreeng...@gmail.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
"Todd Matsumoto" wrote The while loop will print each index of the list. No, the while does nothing with list indexes, that is entirely down to the programmer. The while loop simply repeats for as long as its test expression evaluates to True. As far as I know there isn't any 'True' or 'False' output from a list. Lists are considered True if they are non empty, in the same way as strings. So the OPs test is perfectly valid while myList: do something to reduce mylist (or use break but then you should use while True) If you want to do something if mylist is empty you can check it like this: if not mylist: ... do something ... Which is the logical inverse of what the OP was testing in his while loop. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
On Mon, Oct 19, 2009 at 2:26 AM, Todd Matsumoto wrote: > The while loop will print each index of the list. No it's printing each element of the list, not the index. > In a way it checks that if the list is empty by printing the items. As far > as I know there isn't any 'True' or 'False' output from a list. > I'm not sure what you mean here because... > > If you want to do something if mylist is empty you can check it like this: > > if not mylist: > An "if" statement checks a boolean state so the list must be evaluating to a boolean somehow. (It does, it's False if it's empty and True otherwise). -Luke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
Wayne wrote: Hi, I think I recall seeing this here, but I wanted to make sure I'm correct. Is the best way to test for an empty list just test for the truth value? I.e. mylist = [1,2,3] while mylist: print mylist.pop() Thanks, Wayne My take is simple: Use the above form if you *know* that mylist is in fact a list. If you don't know its type for sure (the name is a clue, but not conclusive ;-) ) then use a more specific test. In your case, you know it's a list, or least something that supports pop(). So your form should be great. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
I don't understand how the while loop efficiently tests if the list is empty. Why would going through the entire list be a good test to simply see find out if the list is empty or not. Wouldn't you want to test the list itself, rather than the contents of it? Cheers, T Original-Nachricht > Datum: Mon, 19 Oct 2009 04:52:40 -0400 > Von: Dave Angel > An: Wayne > CC: "tutor@python.org" > Betreff: Re: [Tutor] Testing for empty list > > > Wayne wrote: > > Hi, I think I recall seeing this here, but I wanted to make sure I'm > > correct. > > Is the best way to test for an empty list just test for the truth value? > > I.e. > > > > mylist = [1,2,3] > > > > while mylist: > >print mylist.pop() > > > > Thanks, > > Wayne > > > > > My take is simple: Use the above form if you *know* that mylist is in > fact a list. If you don't know its type for sure (the name is a clue, > but not conclusive ;-) ) then use a more specific test. > > In your case, you know it's a list, or least something that supports > pop(). So your form should be great. > > DaveA > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- GRATIS für alle GMX-Mitglieder: Die maxdome Movie-FLAT! Jetzt freischalten unter http://portal.gmx.net/de/go/maxdome01 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
Hi, please don't top-post. Todd Matsumoto wrote: > I don't understand how the while loop efficiently tests if the list is > empty. It doesn't. It only tests a condition. And the result of the condition is determined by the list itself, which knows if it's empty or not. Stefan ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] introspecting an object for method's name?
On Sunday, October 18, 2009, Serdar Tumgoren wrote: > Hi everyone, > I'm trying to create a generic logging function, and I'm able to get > at the name of the module and class using the built-in attributes > __module__, __class__, and __name__. > > But I wasn't sure how to also grab the name of the function or method, > so that when an error occurs, I can log the name of the failing method > as well. Using sys._getframe() you can get the name of the current function or the name of the calling function. Getting the name of the caller means you can wrap your logger into a function. See this recipe: http://code.activestate.com/recipes/66062/ Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] introspecting an object for method's name?
Kent Johnson wrote: On Sunday, October 18, 2009, Serdar Tumgoren wrote: Hi everyone, I'm trying to create a generic logging function, and I'm able to get at the name of the module and class using the built-in attributes __module__, __class__, and __name__. But I wasn't sure how to also grab the name of the function or method, so that when an error occurs, I can log the name of the failing method as well. Using sys._getframe() you can get the name of the current function or the name of the calling function. Getting the name of the caller means you can wrap your logger into a function. See this recipe: http://code.activestate.com/recipes/66062/ Or just use the built-in logging module which lets you specify the containing function name as one of its formatting keywords: http://docs.python.org/library/logging.html#formatter-objects TJG ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] introspecting an object for method's name?
> Or just use the built-in logging module which lets you specify > the containing function name as one of its formatting keywords: > > http://docs.python.org/library/logging.html#formatter-objects > Aha! I had skimmed the logging docs, but hadn't gone far enough down to notice the %(funcName)s formatting option. Thanks to one and all for the suggestions! Serdar ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] introspecting an object for method's name?
On Mon, Oct 19, 2009 at 8:40 AM, Tim Golden wrote: > Or just use the built-in logging module which lets you specify > the containing function name as one of its formatting keywords: > > http://docs.python.org/library/logging.html#formatter-objects Sweet! And much better than rolling your own logger. Kent ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
Wayne wrote: Hi, I think I recall seeing this here, but I wanted to make sure I'm correct. Is the best way to test for an empty list just test for the truth value? I.e. mylist = [1,2,3] while mylist: print mylist.pop() Thanks, Wayne My take is simple: Use the above form if you *know* that mylist is in fact a list. If you don't know its type for sure (the name is a clue, but not conclusive ;-) ) then use a more specific test. In your case, you know it's a list, or least something that supports pop(). So your form should be great. DaveA Hello all, Just a newbie question, but when would you test for an empty list? Is it part of a code error detection or an error check to make sure that there is user input? Couldn't you just use something like: while len(mylist) > 0: continue program else: print "mylist is empty or is my lack of python knowledge preventing me from seeing the meaning of the question? Thanks in advance, Katt ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Python List Help
Hi all, I am a PHP developer that just started learning Python for a specific application and the transition has been pretty easily assisted by google, but I just dont see the issue with this one? Ive got a list that created and populate in a loop that shows the correct info when I print it, but if I try to print array[0], it says the list index is out of range. Here is the code snippet. Basically, I have a link here that I am pulling the href info from and splitting it up, only keeping the 5th value, which I am then adding to the playerid array. playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) stats = test.findAll(text=True) print len(playerid) ß this shows the expected result print playerid[0] ßthis kills the script 33 print len(playerid) 34 print playerid[0] 35 playerid = [] : list index out of range args = ('list index out of range',) message = 'list index out of range' If I change the print playerid[0] to print playerid[1], same error, but if I change it to print playerid[2] or higher, it will show the same error, but the playerid= [] will show the actual list values in the debug. Any help would be appreciated, thank you! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
2009/10/19 Katt > > Hello all, > > Just a newbie question, but when would you test for an empty list? Is it > part of a code error detection or an error check to make sure that there is > user input? > > Couldn't you just use something like: > > while len(mylist) > 0: > continue program > else: > print "mylist is empty > > or is my lack of python knowledge preventing me from seeing the meaning of > the question? > > Thanks in advance, > > Katt > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor There's various situations, consider this simple implementation of a queue of tasks that need completing: from abc import abstractmethod class QueueableItem(object): """abstract base class to allow tasks to be queued""" def queue(self): """Add the task to the queue""" queue.append(self) def completed(self): """Mark the task as completed, and remove it from the queue""" queue.remove(self) @abstractmethod def run(self, *args): """complete the queued task, should call self.completed() after running.""" class PrintTask(QueueableItem): def __init__(self, data): self.data = data def run(self, *args): print self.data self.completed() def processQueue(): while queue: queue[0].run() print "Queue Processed\n" if __name__ == "__main__": queue = [] PrintTask("Hello").queue() PrintTask("World").queue() processQueue() In this situtation, the while loop could be substituted for a for loop, but consider the following task: class TaskThePrecedent(QueueableItem): def run(self, *args): if precedentCompleted(): #do stuff self.completed() else: queue.insert(0, PrecedentTask()) Yes, the precedentTask code could be pasted into the else block, but what if more than one class used that precedent, or the precedent had precedents itself, which in turn were used by multiple classes? OK, That was pretty contrieved, and I'm sure other tutors can come up with better examples, but I think it gives an idea of one of the many situtations in which you might need to test for a lists contents. I also put far too much work into it. "Simple", my foot. -- Rich "Roadie Rich" Lovely There are 10 types of people in the world: those who know binary, those who do not, and those who are off by one. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] "if clause" in list comprehensions.
Hello, The other day I was making a script and decided to use a list compreehension and I found out that this code: mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item a = [upperfy(item) for item in mylist] My question is? Am I solving the problem in the right way? Am I missing something? Thanks for all the help I've been getting as a newcomer. Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] updating Unix config file
Hi All. The below script seems to work well enough to use but I'm wondering if I'm doing the file edit stuff in a "kosher" manner. I was just reading the Lutz O'Reilly "Learning" book and remembered that strings are immutable. So how was I able to change the strings for my dotted quad? I did not explicitly open a separate file in /tmp and then overwrite the ipf.conf file which seemed like the safer way. Yet somehow the below syntax works. Also I need to figure out how to update the LASTKNOWN variable after my IP changes. Thanks for any advice. import socket # import fileinput import subprocess import string import re SENDMAIL = "/usr/sbin/sendmail" CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] LASTKNOWN = '173.48.204.168' if CURRENT == LASTKNOWN: print 'Nevermind.' subprocess.sys.exit() else: cf = open("/etc/ipf.conf", "r") lns = cf.readlines() lns = "".join(lns) # close it so that we can open for writing later lns = re.sub(LASTKNOWN, CURRENT, lns) cf = open("/etc/ipf.conf", "w") cf.write(lns) cf.close() subprocess.call('/sbin/ipf -Fa -f /etc/ipf.conf', shell=True) subprocess.call('/sbin/ipnat -CF -f /etc/ipnat.conf', shell=True) ptchew = subprocess.Popen("%s -t" % SENDMAIL, "w") ptchew.write("To: m...@blisses.org\n") ptchew.write("Subject: YOUR IP ADDRESS HAS CHANGED\n") ptchew.write("\n") # blank line separating headers from body ptchew.write("Your IP address has changed to: ") ptchew.write(CURRENT) ptchew.write(time.asctime()) ptchew = p.close() -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
2009/10/19 Eduardo Vieira : > mylist = ['John', 'Canada', 25, 32, 'right'] > a = [item.upper() for item in mylist if type(item) == type('good')] Usually it is recommended to use hasattr() instead of type() hasattr(s, 'upper') > returned this: ['JOHN', 'CANADA', 'RIGHT'] > I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] > So, actually the "if" acted like a filter. > In order to use a list comprehension I created this function instead. > def upperfy(item) > try: > item = item.upper() > except AttributeError: > pass > return item I would move return item under the except and remove the pass, other might disagree on this. > a = [upperfy(item) for item in mylist] You can use this which gives the added benefit that you can document why you are using this within the function. But you can include else in list comprehension. a = [item.upper() if hasattr(item, 'upper') else item for item in mylist] Your case it might be "overkill" to use the function. Greets Sander ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 11:39 AM, Eduardo Vieira wrote: > Hello, > The other day I was making a script and decided to use a list > compreehension and I found out that this code: > mylist = ['John', 'Canada', 25, 32, 'right'] > a = [item.upper() for item in mylist if type(item) == type('good')] > returned this: ['JOHN', 'CANADA', 'RIGHT'] > I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] > What type is 'good' ? What type is 25? Also, perhaps you misunderstand what a list comprehension does: a = [item for item in mylist if type(item) == type('good')] will look at the first item - is it of type string? if so then it's added to the list, otherwise it's ignored. So, actually the "if" acted like a filter. > In order to use a list comprehension I created this function instead. > def upperfy(item) >try: >item = item.upper() >except AttributeError: >pass >return item > > a = [upperfy(item) for item in mylist] > > My question is? Am I solving the problem in the right way? Am I > missing something? > Thanks for all the help I've been getting as a newcomer. I don't know if it's the "right" way, but it looks fine to me. HTH, Wayne ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python List Help
Mike Sweany wrote: Hi all, I am a PHP developer that just started learning Python for a specific application and the transition has been pretty easily assisted by google, but I just don’t see the issue with this one? I’ve got a list that created and populate in a loop that shows the correct info when I print it, but if I try to print array[0], it says the list index is out of range. Here is the code snippet. Basically, I have a link here that I am pulling the href info from and splitting it up, only keeping the 5th value, which I am then adding to the playerid array. playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) stats = test.findAll(text=True) print len(playerid) ß this shows the expected result print playerid[0] ßthis kills the script 33 print len(playerid) 34 print playerid[0] 35 playerid = [] : list index out of range args = ('list index out of range',) message = 'list index out of range' If I change the print playerid[0] to print playerid[1], same error, but if I change it to print playerid[2] or higher, it will show the same error, but the playerid= [] will show the actual list values in the debug. Any help would be appreciated, thank you! I'm very confused about your formatting. You seem to be using tabs with a large column setting (prefer 4 columns, and tabs should become spaces in the editor). But there's no context. So this stuff is indented, but it's not inside a function?? And the numbers 33, 34, and 35, what are they from? What debugger are you running, that somehow displays list values when you assign an empty list to playerid? That makes no sense. If it's an exotic debugger, then perhaps you should be doing this straight from the python interpreter. I suggest that until you're comfortable enough with python to know what to include, that you post exactly what happened, without trying so hard to customize it. Show the file, in its entirety (if it's too big, then you would need a smaller example). And put markers at begin and end so we can see what part is the file. Then if you're running from the interpreter prompt, show the whole session, from import to the traceback error. Note that if you want to print variables from the imported program, you'd use >>> print mymodule.playerid The following is not intended to be good programming, it's intended to encapsulate what you already had, with some initialization to avoid needing other stuff that's presumably irrelevant here. ***file stuff2.py #!/usr/bin/env python #-*- coding: utf-8 -*- link0 = {"href":"this /is /a /test/of the stuff/before here"} link1 = {"href":"this /is /a /test/different stuff/before here"} link2 = {"href":"this /is /a /test/other stuff/before here"} playerlink = [link0, link1, link2] players = len(playerlink) def doit(): global playerid playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) print len(playerid) # this shows the expected result print playerid[0] #this gets an exception if __name__ == "__main__": doit() *** end file * And now the interpreter session: M:\Programming\Python\sources\dummy>python26 ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import stuff2 >>> stuff2.doit() 3 of the stuff >>> print len(stuff2.playerid) 3 >>> print stuff2.playerid[0] of the stuff >>> Of course, I didn't get any error. But if you do, your transcript should be enough information for people to better tell why. One more thing: copy/paste, don't retype. Otherwise you may obscure the problem or introduce others. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Testing for empty list
"Katt" wrote Just a newbie question, but when would you test for an empty list? When you are processing a list such that you are deleting items as you go. When the list is empty stop processing! And Python helps you do that by treating an empty list as a False boolean value so you can do while myList: process items from myList This will keep on processing myList until all the items have been deleted. Note, this could be more times than the number of items in the list...for example: counter = 0 myList = [12,24] nines = [] while myList: counter += 1 print "iteration number", counter index = 0 while index < len(myList):# copes with disappearing members if myList[index] % 9 == 0: # is it divisible by 9? nines.append(myList[index]) del(myList[index]) # remove from list else: myList[index] -= 1 index += 1 print nines while len(mylist) > 0: continue program else: print "mylist is empty That is the same as while mylist: continue program else: print 'mylist is empty' HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
"Matt Herzog" wrote remembered that strings are immutable. So how was I able to change the strings for my dotted quad? You didn't. LASTKNOWN = '173.48.204.168' lns = cf.readlines() lns = "".join(lns) lns = re.sub(LASTKNOWN, CURRENT, lns) I assume this is the line in question? sub() returns a new string containing the substitutions. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
"Sander Sweers" wrote mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] Usually it is recommended to use hasattr() instead of type() hasattr(s, 'upper') Nope, they do completely different things I think you might be thinking of isinstance() which can be used instead of type(). I see you use hasattr as a means of testing for a method but that is still different from testing type - the method names might be the same but the functions be completely different in effect! returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. It is intended to be used as a filter. In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item I would move return item under the except and remove the pass, other might disagree on this. I would :-) Doing that would result in None being returned for each successful conversion. The OPs code is correct (even if unnecessary) a = [upperfy(item) for item in mylist] a = [item.upper() if type(item) == str else item for item in mylist] should do it I think. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
2009/10/19 Alan Gauld : >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! Indeed, I was and stand corrected. >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> try: >>> item = item.upper() >>> except AttributeError: >>> pass >>> return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) I missed that the try: did not return anything. I was thinking more of something like this. def upperfy(item): try: item.upper() return item except AttributeError: return item Thanks for correcting me! Greets Sander PS: Note to self, never reply in a hurry :-( ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On 10/19/2009 12:20 PM Alan Gauld said... "Sander Sweers" wrote mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] Usually it is recommended to use hasattr() instead of type() hasattr(s, 'upper') Nope, they do completely different things I think you might be thinking of isinstance() which can be used instead of type(). I see you use hasattr as a means of testing for a method but that is still different from testing type - the method names might be the same but the functions be completely different in effect! returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. It is intended to be used as a filter. In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item I would move return item under the except and remove the pass, other might disagree on this. I would :-) Doing that would result in None being returned for each successful conversion. The OPs code is correct (even if unnecessary) a = [upperfy(item) for item in mylist] a = [item.upper() if type(item) == str else item for item in mylist] should do it I think. or even a = [ str(item).upper() for item in mylist ] Emile HTH, ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille wrote: > On 10/19/2009 12:20 PM Alan Gauld said... > > >> "Sander Sweers" wrote >> >> mylist = ['John', 'Canada', 25, 32, 'right'] a = [item.upper() for item in mylist if type(item) == type('good')] >>> >>> Usually it is recommended to use hasattr() instead of type() >>> hasattr(s, 'upper') >>> >> >> Nope, they do completely different things >> I think you might be thinking of isinstance() which can be used instead of >> type(). I see you use hasattr as a means of testing for a method but that is >> still different from testing type - the method names might be the same but >> the functions be completely different in effect! >> >> returned this: ['JOHN', 'CANADA', 'RIGHT'] I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] So, actually the "if" acted like a filter. >>> >> It is intended to be used as a filter. >> >> In order to use a list comprehension I created this function instead. def upperfy(item) try: item = item.upper() except AttributeError: pass return item >>> >> I would move return item under the except and remove the pass, other >>> might disagree on this. >>> >> >> I would :-) >> Doing that would result in None being returned for each successful >> conversion. The OPs code is correct (even if unnecessary) >> >> a = [upperfy(item) for item in mylist] >>> >> a = [item.upper() if type(item) == str else item for item in mylist] >> >> should do it I think. >> > > or even > > a = [ str(item).upper() for item in mylist ] > > Emile > > > >> HTH, >> >> >> > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Lambda can save the day to keep everything on one line, and leave variable type the same: mylist = ['John', 'Canada', 25, 32, 'right'] new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in x] >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] Vince ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 2:14 PM, vince spicer wrote: > > > On Mon, Oct 19, 2009 at 1:58 PM, Emile van Sebille wrote: > >> On 10/19/2009 12:20 PM Alan Gauld said... >> >> >>> "Sander Sweers" wrote >>> >>> mylist = ['John', 'Canada', 25, 32, 'right'] > a = [item.upper() for item in mylist if type(item) == type('good')] > Usually it is recommended to use hasattr() instead of type() hasattr(s, 'upper') >>> >>> Nope, they do completely different things >>> I think you might be thinking of isinstance() which can be used instead >>> of type(). I see you use hasattr as a means of testing for a method but that >>> is still different from testing type - the method names might be the same >>> but the functions be completely different in effect! >>> >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] > I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] > So, actually the "if" acted like a filter. > >>> It is intended to be used as a filter. >>> >>> In order to use a list comprehension I created this function instead. > def upperfy(item) > try: > item = item.upper() > except AttributeError: > pass > return item > >>> I would move return item under the except and remove the pass, other might disagree on this. >>> >>> I would :-) >>> Doing that would result in None being returned for each successful >>> conversion. The OPs code is correct (even if unnecessary) >>> >>> a = [upperfy(item) for item in mylist] > >>> a = [item.upper() if type(item) == str else item for item in mylist] >>> >>> should do it I think. >>> >> >> or even >> >> a = [ str(item).upper() for item in mylist ] >> >> Emile >> >> >> >>> HTH, >>> >>> >>> >> ___ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > Lambda can save the day to keep everything on one line, and leave variable > type the same: > > mylist = ['John', 'Canada', 25, 32, 'right'] > new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in > mylist ] > > >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] > > Vince > wrong var name "x", fixed ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 9:20 PM, Alan Gauld wrote: > > > "Sander Sweers" wrote > > mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >>> >> >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') >> > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! When I read Sander's advice, I thought it would be the sensible thing to do when working with strings that could be either vanilla 8-bit strings or Unicode strings. For example: >>> my_list = ['a string', u'another string', 42] >>> print [item.upper() for item in my_list if hasattr(item, 'upper')] ['A STRING', u'ANOTHER STRING'] >>> print [item.upper() for item in my_list if type(item) == type('good')] ['A STRING'] Thinking of it, the same result could be achieved with 'if isinstance(item, basestring)'. Is there any compelling reason to write: [item.upper() for item in my_list if isinstance(item, basestring)] rather than the following? [item.upper() for item in my_list if hasattr(item, 'upper')] Emmanuel ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On or about 2009 Oct 19, at 3:57 PM, Sander Sweers indited: I missed that the try: did not return anything. I was thinking more of something like this. def upperfy(item): try: item.upper() return item except AttributeError: return item Thanks for correcting me! Depending on what 'item' is, item.upper() might return an new thing, but the code looks as if you're expecting .upper() to modify item itself. If item is a string, item.upper() will return a new string and leave item alone (since strings are immutable in Python). -Doug ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
On Mon, Oct 19, 2009 at 1:20 PM, Alan Gauld wrote: > > "Sander Sweers" wrote > >>> mylist = ['John', 'Canada', 25, 32, 'right'] >>> a = [item.upper() for item in mylist if type(item) == type('good')] >> >> Usually it is recommended to use hasattr() instead of type() >> hasattr(s, 'upper') > > Nope, they do completely different things > I think you might be thinking of isinstance() which can be used instead of > type(). I see you use hasattr as a means of testing for a method but that is > still different from testing type - the method names might be the same but > the functions be completely different in effect! > >>> returned this: ['JOHN', 'CANADA', 'RIGHT'] >>> I was expecting this: ['JOHN', 'CANADA', 25, 32, 'RIGHT'] >>> So, actually the "if" acted like a filter. > > It is intended to be used as a filter. > >>> In order to use a list comprehension I created this function instead. >>> def upperfy(item) >>> try: >>> item = item.upper() >>> except AttributeError: >>> pass >>> return item > >> I would move return item under the except and remove the pass, other >> might disagree on this. > > I would :-) > Doing that would result in None being returned for each successful > conversion. The OPs code is correct (even if unnecessary) > >>> a = [upperfy(item) for item in mylist] > > a = [item.upper() if type(item) == str else item for item in mylist] > > should do it I think. > > HTH, > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Thanks for all the guidance. I'm glad I learned I could use "else" in the list comp. after all. I thought I could, but when I tried it, I got it wrong and forgot how I did it. Yeah, I had an impression that a function was unnecessary in this case, but didn't know how to get around it. To: Emmanuel: Thanks for your remark in the case of unicode. In my code that wasn't a problem, but it's something to consider. Regards, Eduardo ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
Is there any compelling reason to write: > >[item.upper() for item in my_list if isinstance(item, basestring)] > >rather than the following? > >[item.upper() for item in my_list if hasattr(item, 'upper')]What happens if >you have an object in your list that has an 'upper' merthod that, say, reboots your PC into an upper level of admin access? Or that sets the bank account credit limit to the upper limit? Your list comprehension will happily run and apply upper to the object but the result may not be what you expected. If you check isinstance you know that you are working with some kind of string at least. (A programmer could still override upper do do some wacky thing but then that programmer is abusing upper, whereas, in the bank account case it's a perfectly valid application of upper() ) Even more to the point the 'upper' that hasattr() finds may not be callable, it could be the upper value of a range for example. Then when you try to use it in the comprehension you will get an error. Alan G.___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
"Emile van Sebille" wrote a = [item.upper() if type(item) == str else item for item in mylist] should do it I think. or even a = [ str(item).upper() for item in mylist ] That was my first attempt but the OP wanted his integers preserved as integers whereas this would convert them to strings. -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
"vince spicer" wrote Lambda can save the day to keep everything on one line, and leave variable type the same: mylist = ['John', 'Canada', 25, 32, 'right'] new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in mylist ] >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] Vince wrong var name "x", fixed ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] "if clause" in list comprehensions.
Ooops, hit send by mistake... "vince spicer" wrote Lambda can save the day to keep everything on one line, and leave variable type the same: mylist = ['John', 'Canada', 25, 32, 'right'] new_list = [(lambda y: y.upper() if hasattr(y, 'upper') else y)(a) for a in mylist ] >> ['JACK', 'CANADA', 25, 32, 'RIGHT'] In what way does lambda help? new_list = [y.upper() if hasattr(y, 'upper') else y for y in mylist] does exactly the same and is shorter. lambda helps if you want to pass a function object around but defining it and immediately calling it means it can be replaced directly by the expression within the lambda. But using hasattr() still has the problem of failing if upper is not a callable attribute (or does something radical like exiting) -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > "Matt Herzog" wrote > > >remembered that strings are immutable. > >So how was I able to change the strings for my dotted quad? > > You didn't. > > >LASTKNOWN = '173.48.204.168' > > lns = cf.readlines() > > lns = "".join(lns) > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > I assume this is the line in question? > sub() returns a new string containing the substitutions. > > HTH, Yes! It sure does help. I just discovered that my script does not exit if the CURRENT IP is the same as the LASTKNOWN IP. -- snip -- CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] -- snip -- Turns out the above is an unreliable way to get the IP of the interface since the machine the above is running on does not have a proper hostname and is a dhcp client on a broadband network. Anyway, I'd like a hint as to how I could convert this: ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() x = string.split(ifcfg_lines[3])[1] to the subprocess module. The os module is going away, right? > > > -- > Alan Gauld > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] updating Unix config file
On Mon, Oct 19, 2009 at 07:51:06PM -0400, Matt Herzog wrote: > On Mon, Oct 19, 2009 at 08:07:47PM +0100, Alan Gauld wrote: > > > > "Matt Herzog" wrote > > > > >remembered that strings are immutable. > > >So how was I able to change the strings for my dotted quad? > > > > You didn't. > > > > >LASTKNOWN = '173.48.204.168' > > > lns = cf.readlines() > > > lns = "".join(lns) > > > lns = re.sub(LASTKNOWN, CURRENT, lns) > > > > I assume this is the line in question? > > sub() returns a new string containing the substitutions. > > > > HTH, > > Yes! It sure does help. I just discovered that my script does not exit if the > CURRENT IP is the same as the LASTKNOWN IP. Please ignore the above. > -- snip -- > CURRENT = socket.getaddrinfo(socket.gethostname(), None)[0][4][0] > -- snip -- > Turns out the above is an unreliable way to get the IP of the interface since > the machine the above is running on does not have a proper hostname and is a > dhcp client on a broadband network. It's unreliable because it uses DNS, I believe. I'm not faulting the author. > > Anyway, I'd like a hint as to how I could convert this: > > ifcfg_lines = os.popen("/sbin/ifconfig fxp0").readlines() > x = string.split(ifcfg_lines[3])[1] > > to the subprocess module. The os module is going away, right? > > > > > > > > -- > > Alan Gauld > > Author of the Learn to Program web site > > http://www.alan-g.me.uk/ > > > > ___ > > Tutor maillist - Tutor@python.org > > To unsubscribe or change subscription options: > > http://mail.python.org/mailman/listinfo/tutor > > -- > The test of a first-rate intelligence is the ability to hold two opposed > ideas in the mind at the same time, and still retain the ability to function. > > -- F. Scott Fitzgerald > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor -- The test of a first-rate intelligence is the ability to hold two opposed ideas in the mind at the same time, and still retain the ability to function. -- F. Scott Fitzgerald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Running Python on a Calculator
Hey tutors. I have a TI-84 plus, and I am making some math tools, and I don't know the native language of the Ti-84, and was wondering, has anyone worked with a version of Python that can run on that small of a processor? Thanks in advance, ~Corey ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python List Help
Thanks for the reply and Tips Dave... I think the formatting came out weird because I didnt specify plain text when I created the email. I'm using Google App Engine and it's internal debugger shows what I posted earlier when the code breaks, I agree that what I am seeing from the debugger makes no sense... Thanks for the tips, I will look at what you have and see if I can make it work... >From top to bottom, I am using BeautifulSoup to parse an html document and what you are seeing is a part of the processing that just didnt jive with practices that I had already carried over and had working with the rest of the code. I dont have it set up to do the import with an interpreter session like you laid out below, basically I am printing the stuff as it goes, it's in a loop and this code is processed multiple times. Honestly, I need to do some reading on how python works as I was plugging along on this script with just a couple of hours into python for this scraping project, but what you have shown me here will help and I will come back to the list after I have a better understanding of what I am doing. Thanks, Mike -Original Message- From: Dave Angel [mailto:da...@ieee.org] Sent: Monday, October 19, 2009 1:35 PM To: Mike Sweany Cc: tutor@python.org Subject: Re: [Tutor] Python List Help Mike Sweany wrote: > Hi all, > > > > I am a PHP developer that just started learning Python for a specific > application and the transition has been pretty easily assisted by google, > but I just dont see the issue with this one? > > > > Ive got a list that created and populate in a loop that shows the correct > info when I print it, but if I try to print array[0], it says the list index > is out of range. > > > > Here is the code snippet. Basically, I have a link here that I am pulling > the href info from and splitting it up, only keeping the 5th value, which I > am then adding to the playerid array. > > > > playerid = [] > > for i in range(0, players): > > player = playerlink[i]['href'] > > breakup = player.split('/') > > playerid.append(breakup[4]) > > > > stats = test.findAll(text=True) > > print len(playerid) ß this shows the expected result > > print playerid[0] ßthis kills the script > > > > > > >33 print len(playerid) > > >34 print playerid[0] > > >35 > > > > playerid = [] > > : list index out of range > args = ('list index out of range',) > message = 'list index out of range' > > If I change the print playerid[0] to print playerid[1], same error, but if I > change it to print playerid[2] or higher, it will show the same error, but > the playerid= [] will show the actual list values in the debug. > > Any help would be appreciated, thank you! > > > > I'm very confused about your formatting. You seem to be using tabs with a large column setting (prefer 4 columns, and tabs should become spaces in the editor). But there's no context. So this stuff is indented, but it's not inside a function?? And the numbers 33, 34, and 35, what are they from? What debugger are you running, that somehow displays list values when you assign an empty list to playerid? That makes no sense. If it's an exotic debugger, then perhaps you should be doing this straight from the python interpreter. I suggest that until you're comfortable enough with python to know what to include, that you post exactly what happened, without trying so hard to customize it. Show the file, in its entirety (if it's too big, then you would need a smaller example). And put markers at begin and end so we can see what part is the file. Then if you're running from the interpreter prompt, show the whole session, from import to the traceback error. Note that if you want to print variables from the imported program, you'd use >>> print mymodule.playerid The following is not intended to be good programming, it's intended to encapsulate what you already had, with some initialization to avoid needing other stuff that's presumably irrelevant here. ***file stuff2.py #!/usr/bin/env python #-*- coding: utf-8 -*- link0 = {"href":"this /is /a /test/of the stuff/before here"} link1 = {"href":"this /is /a /test/different stuff/before here"} link2 = {"href":"this /is /a /test/other stuff/before here"} playerlink = [link0, link1, link2] players = len(playerlink) def doit(): global playerid playerid = [] for i in range(0, players): player = playerlink[i]['href'] breakup = player.split('/') playerid.append(breakup[4]) print len(playerid) # this shows the expected result print playerid[0] #this gets an exception if __name__ == "__main__": doit() *** end file * And now the interpreter session: M:\Programming\Python\sources\dummy>python26 ActivePython 2.6.2.2 (