[Tutor] lists - append - unique and sorted

Kent Johnson kent37 at tds.net
Wed Jun 6 19:38:46 CEST 2007


roberto wrote:
> hi,
> 
> can i append a item to a list using criterias:
> 
> - UNIQUE - if there already exist don't append

if item not in lst: lst.append(item)

"item not in lst" uses a linear search so performance deteriorates as 
len(lst) grows. If you don't care about the order of elements in lst, a 
set give better performance.

> and/or
> 
> - SORTED - INSERT in the correct place using some criteria?

Resorting is pretty fast, or see the bisect module.

Kent


More information about the Tutor mailing list