Append to python List

Chris Angelico rosuav at gmail.com
Thu May 9 02:52:42 EDT 2013


On Thu, May 9, 2013 at 4:36 PM, RAHUL RAJ <omrahulrajcse at gmail.com> wrote:
> output=[x for x in sample2 if x not in output]
>
> output=[]
> for x in sample2:
>   if x not in output:
>      output.append(x)

The first one constructs a list, then points the name 'output' at it.
The second one builds up a list, with 'output' pointing at it all the
way. Your first one is more like:

sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
output=[]
_temp=[]
for x in sample2:
  if x not in output:
     _temp.append(x)
output=_temp

You may want to consider using a set, instead.

>>> {x+y for x in range(1,10) for y in range(1,10) if x!=y}
{3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}

ChrisA



More information about the Python-list mailing list