[Tutor] Two dimensional lists
Mats Wichmann
mats at wichmann.us
Mon Nov 2 08:56:25 EST 2020
On 11/2/20 3:08 AM, Alan Gauld via Tutor wrote:
>
> On 02/11/2020 09:33, Phil wrote:
>>
>> Declaring a two dimensional array in C takes one line of code, e.g. int
>> b[5][5].
>>
>> The equivalent in Python takes 7 lines or one long line:
>>
>> b = [
>> [0] * 5,
>> [0] * 5,
>> [0] * 5,
>> [0] * 5,
>> [0] * 5,
>> ]
>>
>> My array is [30] [25] which means many lines of code, something I want
>> to avoid. Creating a numpy array is also one line of code.
>
> The point is that you don;t in general declare arrays in Python. You
> build them as needed.
>
> So to build the array above you would more likely writer:
>
>
> b = [[0]*5 for row in range(5)]
>
> Which creates a list b that contains 5 rows each of which is a list of 5
> zeros.
>
> If you need to initialize an X by Y table then you would do it:
>
> xy = [[0]*X for row in range(Y)]
>
> Still one line and flexible enough to cope with any sizes.
>
> And you can extend that technique to as many dimensions as you need.
The useful itertools module also has something to help with this
(repeat). In general, you have to be a little careful when constructing
lists-of-lists when the members are mutable objects, rather than ints as
here. But perhaps that's for a little later on in the learning journey...
More information about the Tutor
mailing list