+ 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}

27th Mar 2018, 9:50 AM
Alex K
Alex K - avatar
2 Answers
+ 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.
27th Mar 2018, 10:00 AM
Rayhan Ahmed
Rayhan Ahmed - avatar
+ 1
2nd one is set that contains only distinct elements
31st Mar 2018, 7:35 AM
Jaber Ahmed
Jaber Ahmed - avatar