Append to python List
RAHUL RAJ
omrahulrajcse at gmail.com
Thu May 9 04:18:51 EDT 2013
Then what about this code part?
[(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
and the following code part:
for x in [1,2,3]:
for y in [3,1,4]:
if x != y:
combs.append((x, y))
On Thursday, May 9, 2013 12:24:24 PM UTC+5:30, Gary Herron wrote:
> On 05/08/2013 11:36 PM, RAHUL RAJ wrote:
>
> > Checkout the following code:
>
> >
>
> > sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
>
> > output=[]
>
>
>
> > output=[x for x in sample2 if x not in output]
>
> This statement is not doing what you expect. It is not building a list
>
> in the variable named output, it is building a list (anonymously) then
>
> binding it to the variable output once it's built. Therefore output is
>
> [] for the whole list building operation.
>
>
>
> The later operation works, because your *are* building the list in place
>
> as you go.
>
>
>
> >
>
> > the output I get is
>
> > 3 4 5 6 7 8 9 10 3 5 6 7 8 9 10 11 4 5 7 8 9 10 11 12 5 6 7 9 10 11 12 13 6 7 8 9 11 12 13 14 7 8 9 10 11 13 14 15 8 9 10 11 12 13 15 16 9 10 11 12 13 14 15 17 10 11 12 13 14 15 16 17
>
> >
>
> > which contains duplicate values.
>
> >
>
> >
>
> >
>
> >
>
> > But if I do like this:
>
> >
>
> > sample2 = [x+y for x in range(1,10) for y in range(1,10) if x!=y]
>
> > output=[]
>
> > for x in sample2:
>
> > if x not in output:
>
> > output.append(x)
>
> >
>
> >
>
> > the value of 'output' I get like this:
>
> > 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
>
> >
>
> > I know that both the programs have the same functionality, but why do I have different outputs?
>
> >
>
> > Please help!
More information about the Python-list
mailing list