Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are these Python notations: `[ [] ] * n` and `(i,)`

Tags:

python

syntax

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?
like image 290
usual me Avatar asked Dec 12 '22 10:12

usual me


1 Answers

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'>
like image 138
TerryA Avatar answered Dec 28 '22 05:12

TerryA