is this pythonic?

pruebauno at latinmail.com pruebauno at latinmail.com
Wed Jan 21 20:18:02 CET 2009


On Jan 21, 12:34 pm, TP <Tribulati... at Paralleles.invalid> wrote:
> alex23 wrote:
> > Try not to use 'dict' or the name of any of the other built-in types
>
> So my list is rather:
> l=[{"title":"to", "color":"blue", "value":2}
> {"title":"ti", "color":"red", "value":"coucou"}]
>
> So, I will rather use your solution:
>
> for index, record in enumerate(l):
>     if record['title'] == 'ti':
>         to_add_in_another_list = l.pop(index)
> another_list.append(to_add_in_another_list )
>
If you have duplicates this will not work. You will have to do
something like this instead:

>>> o=[]
>>> i=0
>>> ln=len(l)
>>> while i<ln:
	if l[i]['title']=='ti':
		o.append(l.pop(i))
		ln-=1
	else:
		i+=1



If you don't have duplicates you can extract the one and exit early:

>>> for index, record in enumerate(l):
	if record['title'] == 'ti':
		to_add_in_another_list = l.pop(index)
		break

I don't know if these are more pythonic, they should be more efficient
for longer lists though.



More information about the Python-list mailing list