how to make a nested list

S

Stef Mientki

P

Peter Pearson

On Thu, 15 Sep 2011 18:57:24 +0200, Stef Mientki wrote:
[snip]
Because the list is much larger, I need a shortcut (ok I can use a for loop)
So I tried
B = 3 * [ [ None, None ]]
B[2][0] = 77
B
[[77, None], [77, None], [77, None]]

which doesn't work as expected.

any suggestions ?
b = [[None, None] for i in range(3)]
b[2][0] = 77
b
[[None, None], [None, None], [77, None]]

If you don't understand why the other approach resulted in
[[77, None], [77, None], [77, None]], feel free to ask. It's
a mistake that I think everybody makes at least once.
 
J

John Ladasky

Stef,

Are your bottom-level lists always of length 2? If so, then you could
use an array, instead of a list of lists.

Python ships with a module called array, but it doesn't allow you to
put non-numeric types into arrays, and it looks like you want the
NoneType. I use the popular numpy module, which does allow non-
numeric types.

You might also like the slice notation that numpy uses for referencing
items in the array. The indices go inside a single set of square
brackets, and are separated by commas.
array([[None, None],
[None, None],
[None, None]], dtype=object)
array([[None, None],
[None, None],
[77, None]], dtype=object)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,778
Messages
2,569,605
Members
45,237
Latest member
AvivMNS

Latest Threads

Top