Can someone please clarify these 2 notations in Python:
[ [] ] * n
: apparently this creates n references to the same object (in this case, an empty list). In which situations is this useful? (i,)
: I have seen some people use this "trailing comma" notation (example: Generating all size k subsets of {0, 1, 2, ... n-1} in the definition of the sets
function). What does it mean?Yes, that does create references to the same object:
>>> L = [[]] * 3
>>> L
[[], [], []]
>>> L[0].append(1)
>>> L
[[1], [1], [1]]
>>> map(id, L)
[4299803320, 4299803320, 4299803320]
This could be useful for whenever you want to create objects with the same items.
(i,)
creates a tuple with the item i
:
>>> mytuple = (5,)
>>> print mytuple
(5,)
>>> print type(mytuple)
<type 'tuple'>
The reason the comma is needed is because otherwise it would be treated as an integer:
>>> mytuple = (5)
>>> print mytuple
5
>>> print type(mytuple)
<type 'int'>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With