comparing elements of a list with a string

Steve Holden steve at holdenweb.com
Thu Sep 27 08:16:59 EDT 2007


Shriphani wrote:
> Hello,
> Would that mean that if I wanted to append all the (date, time) tuples
> to a list, I should do something like:
> 
> for file in list_of_backup_files:
>     some_list.append(file)

That would be one way to do it (assuming you started with some_list as 
an empty list). But a faster way would be to use a list comprehension 
and say

some_list = [f for f in list_of_backup_files]

> By the way I did this:
> 
> def listAllbackups(filename):
> 	list_of_backups = glob(home+'/Desktop/backupdir/*%s*'%filename)
> 	for element in list_of_back:
> 		if element.find(file) != -1:
> 			date_components = element.split('-')[-4:-1]
> 			date = str(date_components[0]) + ":" + str(date_components[1]) +
> ":" + str(date_components[2])
> 			time = element.split('-')[-1]
> 			yield (date, time)
> print listAllbackups('fstab')
> 
> 
> I ran it in the terminal and I got:
> 
> <generator object at 0x81ed58c>
> 
> Why does it do that and not just print out all the values of (date,
> time)

Because the generator object returned by the function has to be used in 
an iterative context to produce its values. Which is why the list 
comprehension produces a list!

If you don't really want a generator then you could just rewrite the 
function to return a list in the first place. You did specifically ask 
"how do I use the yield statement ...". If you are going to iterate o 
ver the list then a generator is typically more memory-efficient 
(because it only produces one element at a time), and can do things that 
a list can't (like deal with a potentially infinite sequence of results).

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline




More information about the Python-list mailing list