+ 2
Why those outputs are different?
print([j for x in range(10) for j in range(x)]) output is: [0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, 8] print({j for x in range(10) for j in range(x)}) output is: {0, 1, 2, 3, 4, 5, 6, 7, 8}
2 odpowiedzi
+ 5
[..] are list here &
{..} are set here
1st one generates list so duplicate values are kept.
2nd one generates a set. and sets cannot have multiple occurrences of the same element. that's why only unique elements are kept.
+ 1
2nd one is set that contains only distinct elements