Build 2D array using append
<p>Python: I would like to read set of data</p>

<pre><code>(category, value): (0, 1) (0, 2) (1, 3) (1, 4)
</code></pre>

<p>To an array as</p>

<pre><code>[[1, 2],[3, 4]]
</code></pre>

<p>Since max number of category is unknown, I would like to create 2D-array dynamically using "append" method.</p>

<p>I wrote a sample code:</p>

<pre><code>data = []
data.append([])

data[0].append(1)
data[0].append(2)

try:
  print (data[1])
except IndexError:
  data.append([])
finally:
  data[1].append(3)
  data[1].append(4)

print(data)
</code></pre>

<p>But, I understand that the code is really ugly because I am using "print" to check the access to <code>data[1]</code>.</p>

<p>Is there any more beautiful solution for this problem?</p>

<p>You can use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a> to do this easily along with a <a href="https://docs.python.org/3/library/functions.html#iter" rel="nofollow"><code>iter</code></a>. </p>

<pre><code>&gt;&gt;&gt; l = [(0, 1), (0, 2), (1, 3), (1, 4)]
&gt;&gt;&gt; i = iter(l)
&gt;&gt;&gt; [[x[1],y[1]] for x,y in zip(i,i)]
[[1, 2], [3, 4]]
</code></pre>

<p>The algorithm here is to iterate over the list of tuples in pairs. This is where <code>iter</code> comes to use. <code>iter</code> creates an iterator that is consumed by the <code>zip</code> function. We then read the tuples into the list comprehension and add only the required two numbers, which is the second indices. </p>

<p>See <a href="http://stackoverflow.com/questions/34835951/what-does-list-comprehension-in-python-mean-how-does-it-work-and-how-can-i-us">What does &quot;list comprehension&quot; in Python mean? How does it work and how can I use it?</a> for more details about them. </p>

python list append