379

I'm beginning python and I'm trying to use a two-dimensional list, that I initially fill up with the same variable in every place. I came up with this:

def initialize_twodlist(foo):
    twod_list = []
    new = []
    for i in range (0, 10):
        for j in range (0, 10):
            new.append(foo)
        twod_list.append(new)
        new = []

It gives the desired result, but feels like a workaround. Is there an easier/shorter/more elegant way to do this?

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
thepandaatemyface
  • 5,034
  • 6
  • 25
  • 30
  • 11
    Just a small (or significant, depending on who is watching) nitpick : lists are not arrays. If you want arrays, use numpy. – Arnab Datta Apr 22 '12 at 01:10
  • [This question is similar](http://stackoverflow.com/questions/3662475/python-multi-dimensional-array-initialization-without-a-loop): it discusses the initialization of multidimensional arrays in Python. – Anderson Green Apr 06 '13 at 03:35
  • @ArnabDatta How would you initialize a multidimensional array in numpy, then? – Anderson Green Apr 06 '13 at 16:17
  • 1
    @AndersonGreen http://docs.scipy.org/doc/numpy/user/basics.creation.html#arrays-creation – Arnab Datta Apr 09 '13 at 07:18
  • You can arrange data in an array like structure in default Python but it's not nearly as efficient or useful as a NumPy array. Especially if you want to deal with large data sets. Here's some documentation http://docs.scipy.org/doc/numpy-1.10.1/user/basics.creation.html – jmdeamer May 16 '16 at 21:08

31 Answers31

562

To initialize a two-dimensional list in Python, use

t = [ [0]*3 for i in range(3)]

But don't use [[v]*n]*n, it is a trap!

>>> a = [[0]*3]*3
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a[0][0]=1
>>> a
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
Benedikt Köppel
  • 4,853
  • 4
  • 32
  • 42
Jason CHAN
  • 6,155
  • 1
  • 13
  • 11
  • 98
    yes, I fell into this trap, too. It's because `*` is copying the `address` of the object (list). – chinuy Jul 19 '17 at 15:58
  • 23
    Upvoted, since this got me. To be clearer, `[[0] * col for _ in range(row)]`. – Abhijit Sarkar Dec 26 '19 at 05:38
  • 2
    Why does it work for the first dimension but not the second? `l = [0] * 3` followed by `l[0] = 1` yields `[1, 0, 0]` just fine. – ArtOfWarfare Sep 13 '20 at 14:27
  • 11
    Found the answer for why the first dimension works but not the second. List multiplication makes a shallow copy. When you assign to an index, it does a proper change, but access does not, so when you do `a[x][y] = 2`, it's accessing, not assigning, for the xth index - only the yth access is actually changed. This page helped me explain with diagrams that are probably better than what I tried explaining in this comment: https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/ – ArtOfWarfare Sep 13 '20 at 14:34
  • @ShivanshRajolia-HeLleR *which* future versions? I just ran into this *garbage/crap* behavior in python3.9 ! – WestCoastProjects Mar 06 '21 at 16:39
  • Why does python not have a professional function to initialise an n dimensional list? – user2585501 Oct 13 '21 at 02:05
  • 1
    Just use Colab and encounter the exact same issue... wasted my 3 hours to debug...But you are a life saver, thank you, upvoted – Near Nov 22 '21 at 15:32
  • do a benchmark, `[ [0]*col for _ in range(row) ]` more faster than `[[0 for _ in range(col)] for _ in range(row)]` – Pegasus Mar 09 '22 at 01:37
  • Doesn't the first * also copy the address of the list and have the same issue? – Abhishek Bhatia Nov 17 '22 at 05:19
417

A pattern that often came up in Python was

bar = []
for item in some_iterable:
    bar.append(SOME EXPRESSION)

which helped motivate the introduction of list comprehensions, which convert that snippet to

bar = [SOME_EXPRESSION for item in some_iterable]

which is shorter and sometimes clearer. Usually, you get in the habit of recognizing these and often replacing loops with comprehensions.

Your code follows this pattern twice

twod_list = []                                       \                      
for i in range (0, 10):                               \
    new = []                  \ can be replaced        } this too
    for j in range (0, 10):    } with a list          /
        new.append(foo)       / comprehension        /
    twod_list.append(new)                           /
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
  • 56
    By the way, [[foo]*10 for x in xrange(10)] can be used to get rid of one comprehension. The problem is that multiplication does a shallow copy, so new = [foo] * 10 new = [new] * 10 will get you a list containing the same list ten times. – Scott Wolchok Mar 07 '10 at 18:24
  • 9
    Similarly, `[foo] * 10` is a list with the same exact `foo` 10 times, which may or may not be important. – Mike Graham Mar 09 '10 at 20:55
  • 3
    we can use the simplest thing: wtod_list = [[0 for x in xrange(10))] for x in xrange(10)] – indi60 Jun 18 '14 at 07:03
  • bar = [SOME EXPRESSION for item in some_iterable (Selection Condition)] – Rudresh Ajgaonkar Sep 13 '16 at 20:49
  • 2
    @Scott Wolchok and Mike Graham - Very important point to make that the multiply with lists copies references to the same list. How do you instantiate an MxN matrix without append? – mdude380 Nov 07 '16 at 22:31
  • 1
    @mdude380 For an MxN array, you'd use numpy http://stackoverflow.com/a/2397147/192839 – Mike Graham Nov 18 '16 at 12:57
  • 3
    For Mike Graham's comment about `[foo] * 10`: This means that this wouldn't work if you're filling an array with random numbers (evaluates `[random.randint(1,2)] * 10` to `[1] * 10` or `[2] * 10` which means that you get an array of all 1s or 2s, instead of a random array. – Tzu Li Jun 06 '19 at 19:24
  • Adding to @TzuLi 's comment, list1 = [ [ 1 ] ]* 10 would store one copy of list i.e [1] in memory and all elements of list1 would refer to the common list. Therefore, if we were to do list1[0].append(2), all elements of list1 would be [1,2]. Answered in detail here: https://stackoverflow.com/a/67842423/10831140 – Ajay May 22 '23 at 14:54
272

You can use a list comprehension:

x = [[foo for i in range(10)] for j in range(10)]
# x is now a 10x10 array of 'foo' (which can depend on i and j if you want)
Adam Rosenfield
  • 390,455
  • 97
  • 512
  • 589
  • 4
    since the size (10) is same its fine, if not the nested loop have to come first [foo for j in range(range_of_j)] for i in range(range_of_i)] – Dineshkumar Mar 28 '15 at 12:48
  • 6
    This answer works fine but I since we iterate `i` for rows and `j` for columns, I think it should be better to swap `i` and `j` in your syntax for better understanding and change the range to 2 different numbers. – DragonKnight Oct 20 '17 at 21:46
153

This way is faster than the nested list comprehensions

[x[:] for x in [[foo] * 10] * 10]    # for immutable foo!

Here are some python3 timings, for small and large lists

$python3 -m timeit '[x[:] for x in [[1] * 10] * 10]'
1000000 loops, best of 3: 1.55 usec per loop

$ python3 -m timeit '[[1 for i in range(10)] for j in range(10)]'
100000 loops, best of 3: 6.44 usec per loop

$ python3 -m timeit '[x[:] for x in [[1] * 1000] * 1000]'
100 loops, best of 3: 5.5 msec per loop

$ python3 -m timeit '[[1 for i in range(1000)] for j in range(1000)]'
10 loops, best of 3: 27 msec per loop

Explanation:

[[foo]*10]*10 creates a list of the same object repeated 10 times. You can't just use this, because modifying one element will modify that same element in each row!

x[:] is equivalent to list(X) but is a bit more efficient since it avoids the name lookup. Either way, it creates a shallow copy of each row, so now all the elements are independent.

All the elements are the same foo object though, so if foo is mutable, you can't use this scheme., you'd have to use

import copy
[[copy.deepcopy(foo) for x in range(10)] for y in range(10)]

or assuming a class (or function) Foo that returns foos

[[Foo() for x in range(10)] for y in range(10)]
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • This seems to be much less readable than any other solution presented. Also, `copy.deepcopy` is not reliable and not something useful very often. – Mike Graham Feb 18 '11 at 21:00
  • 4
    @Mike, did you miss the part in bold? if foo is mutable, none of the other answers here work (unless you are not mutating foo at all) – John La Rooy Feb 18 '11 at 22:48
  • 1
    You cannot correctly copy arbitrary objects using `copy.deepcopy`. You need a plan specific to your data if you have an arbitrary mutable object. – Mike Graham Feb 22 '11 at 17:22
  • 1
    If you need speed that badly in a loop, it may be time to use Cython, weave, or similar... – james.haggerty Oct 21 '12 at 07:10
  • This is also useful in case you want to initialise lists to the same random integer – kon psych Apr 17 '13 at 15:00
  • @MikeGraham FYI python 2.5 made this more useful. See http://stackoverflow.com/questions/15684881/python-implementation-of-shallow-and-deep-copy-constructors -- a custom class for which deepcopy's default behavior is wrong should implement `__ deepcopy __`. That is where "the plan specific to data type" belongs. gnibbler: Thanks -- The deepcopy solution is perfect for the common mutable case where foo is an empty list! – ToolmakerSteve Dec 08 '13 at 18:36
  • How exactly would I use the syntax of the first line? I just get a "NameError: name 'foo' is not defined". Is a `foo = None` before this line the right way to go? (at least it all seems to work as expected then) **EDIT**: Ahh, I got it. The field gets initialised with the value I assign the variable first. So a `foo = 0` at the beginning would init the 2d-array with zeros... Never mind :) – mozzbozz Sep 15 '14 at 14:50
  • 1
    @JohnLaRooy i think you interchanged `x` and `y`. Shouldn't it be `[[copy.deepcopy(foo) for y in range(10)] for x in range(10)]` – user3085931 Apr 09 '16 at 12:17
  • Could anyone quote the documentation on [[foo]*10]*10? I understand why it does not work, but then why does [foo]*10 create 10 different objects? I thought all objects are pointer types in Python... and where exactly is * documented? – Nils May 06 '18 at 11:59
  • 1
    @Nils `[foo]*10` doesn't create 10 different objects - but it's easy to overlook the difference in the case where foo is immutable, like an `int` or `str`. – John La Rooy May 06 '18 at 23:09
  • Thx for the explanation! Now where is this documented? Googling for * does not really work for me. – Nils May 07 '18 at 07:01
75

To initialize a two-dimensional array in Python:

a = [[0 for x in range(columns)] for y in range(rows)]
Vipul
  • 4,038
  • 9
  • 32
  • 56
  • 6
    To initialize all values to 0, just use `a = [[0 for x in range(columns)] for y in range(rows)]`. – ZX9 Sep 21 '16 at 15:33
  • `[[0 for x in range(cols)] for y in range(rows)]` is slow, use `[ [0]*cols for _ in range(rows)]` – Pegasus Mar 09 '22 at 01:32
39
[[foo for x in xrange(10)] for y in xrange(10)]
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 1
    xrange() has been removed in python3.5 – Miae Kim Jan 06 '16 at 16:27
  • 1
    why this doesn't work: [0 * col] * row. When I modify some element it replicates at other places. But I don't understand why? – code muncher Apr 29 '16 at 19:50
  • Because that does exactly the same thing as the code in the question. – Ignacio Vazquez-Abrams Apr 29 '16 at 19:54
  • 4
    @codemuncher The reason that `[[0] * col] * row` doesn't do what you want is because when you initialize a 2d list that way, Python will not create distinct copies of each row. Instead it will init the outer list with pointers to the same copy of `[0]*col`. Any edit you make to one of the rows will then be reflected in the remaining rows since they are all actually pointing to the same data in memory. – Addie May 29 '17 at 06:12
  • Just a thought but aren't all these lists no good for appending to? Ie. if i want an empty 2D list of dimension 3 *6 and want to append to index[0][0], [1][0], [2][0] and so on to fill up all 18 elements, none of these answers will work right? – mLstudent33 Nov 16 '19 at 05:00
25

Usually when you want multidimensional arrays you don't want a list of lists, but rather a numpy array or possibly a dict.

For example, with numpy you would do something like

import numpy
a = numpy.empty((10, 10))
a.fill(foo)
Mike Graham
  • 73,987
  • 14
  • 101
  • 130
  • 5
    Although `numpy` is great, I think it might be a bit of overkill for a beginner. – Esteban Küber Mar 07 '10 at 17:42
  • 3
    numpy provides a multidimensional array type. Building a good multidimensional array out of lists is possible but less useful and harder for a beginner than using numpy. Nested lists are great for some applications, but aren't usually what someone wanting a 2d array would be best off with. – Mike Graham Mar 07 '10 at 17:46
  • 1
    after a few years of occasionally doing serious python apps the quirks of standard python arrays seem to warrant just going ahead with `numpy`. +1 – WestCoastProjects Aug 24 '17 at 18:23
20

For those who are confused why [['']*m]*n is not good to use.

Python uses a system known as “Call by Object Reference” or “Call by assignment”.(More info)

Best way is [['' for i in range(columns)] for j in range(rows)]
This will solve all the problems.

For more Clarification
Example:

>>> x = [['']*3]*3
[['', '', ''], ['', '', ''], ['', '', '']]
>>> x[0][0] = 1
>>> print(x)
[[1, '', ''], [1, '', ''], [1, '', '']]
>>> y = [['' for i in range(3)] for j in range(3)]
[['', '', ''], ['', '', ''], ['', '', '']]
>>> y[0][0]=1
>>> print(y)
[[1, '', ''], ['', '', ''], ['', '', '']]
Tushar
  • 880
  • 9
  • 17
11

You can do just this:

[[element] * numcols] * numrows

For example:

>>> [['a'] *3] * 2
[['a', 'a', 'a'], ['a', 'a', 'a']]

But this has a undesired side effect:

>>> b = [['a']*3]*3
>>> b
[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
>>> b[1][1]
'a'
>>> b[1][1] = 'b'
>>> b
[['a', 'b', 'a'], ['a', 'b', 'a'], ['a', 'b', 'a']]
hithwen
  • 2,154
  • 28
  • 46
  • 14
    In my experience, this "undesirable" effect is often a source of some very bad logical errors. In my opinion, this approach should be avoided, instead @Vipul's answer is much better. – Alan Turing Jun 20 '15 at 19:28
  • this approach works good , why in comments some people refer it is as bad ? – Bravo Oct 25 '17 at 04:12
  • 2
    Because of the undersired side effect, you cannot really treat it as a matrix. If you dont need to alter the contents then it'll be all right. – hithwen Nov 22 '17 at 00:59
  • this is bad because you are soft-copying the same row in your matrix and changing one element will change all the rest. – Yar Apr 24 '22 at 17:18
10
twod_list = [[foo for _ in range(m)] for _ in range(n)]

for n is number of rows, and m is the number of column, and foo is the value.

Moustafa Saleh
  • 178
  • 2
  • 7
8

Code:

num_rows, num_cols = 4, 2
initial_val = 0
matrix = [[initial_val] * num_cols for _ in range(num_rows)]
print(matrix) 
# [[0, 0], [0, 0], [0, 0], [0, 0]]

initial_val must be immutable.

Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142
8

If it's a sparsely-populated array, you might be better off using a dictionary keyed with a tuple:

dict = {}
key = (a,b)
dict[key] = value
...
btk
  • 3,158
  • 2
  • 29
  • 30
6
t = [ [0]*10 for i in [0]*10]

for each element a new [0]*10 will be created ..

Amit K Bist
  • 6,760
  • 1
  • 11
  • 26
user9269722
  • 81
  • 1
  • 2
4

use the simplest think to create this.

wtod_list = []

and add the size:

wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]

or if we want to declare the size firstly. we only use:

   wtod_list = [[0 for x in xrange(10)] for x in xrange(10)]
warped
  • 8,947
  • 3
  • 22
  • 49
indi60
  • 867
  • 4
  • 17
  • 34
4

Incorrect Approach: [[None*m]*n]

>>> m, n = map(int, raw_input().split())
5 5
>>> x[0][0] = 34
>>> x
[[34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None], [34, None, None, None, None]]
>>> id(x[0][0])
140416461589776
>>> id(x[3][0])
140416461589776

With this approach, python does not allow creating different address space for the outer columns and will lead to various misbehaviour than your expectation.

Correct Approach but with exception:

y = [[0 for i in range(m)] for j in range(n)]
>>> id(y[0][0]) == id(y[1][0])
False

It is good approach but there is exception if you set default value to None

>>> r = [[None for i in range(5)] for j in range(5)]
>>> r
[[None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None], [None, None, None, None, None]]
>>> id(r[0][0]) == id(r[2][0])
True

So set your default value properly using this approach.

Absolute correct:

Follow the mike's reply of double loop.

Community
  • 1
  • 1
patilnitin
  • 1,151
  • 10
  • 14
4

To initialize a 2-dimensional array use: arr = [[]*m for i in range(n)]

actually, arr = [[]*m]*n will create a 2D array in which all n arrays will point to same array, so any change in value in any element will be reflected in all n lists

for more further explanation visit : https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/

Abhimanyu
  • 51
  • 2
  • Objection: whereas arr = `[[0]*3 for i in range(3)]` creates `[[0, 0, 0], [0, 0, 0], [0, 0, 0]]`, `arr = [[]*3 for i in range(3)]` creates `[[], [], []]` so you cannot reference arr[2][2], only arr[2], i.e. this is one-dimensional. – Aendie Apr 19 '23 at 19:24
4

Initializing a 2D matrix of size m X n with 0

m,n = map(int,input().split())
l = [[0 for i in range(m)] for j in range(n)]
print(l)
valkyrie55
  • 355
  • 4
  • 10
4

I use it this way to create MxN matrix where m = number(rows) and n = number(columns).

arr = [[None]*(n) for _ in range(m)]
Nishan B
  • 627
  • 7
  • 11
3
Matrix={}
for i in range(0,3):
  for j in range(0,3):
    Matrix[i,j] = raw_input("Enter the matrix:")
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Sparsh
  • 31
  • 2
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Ajean Mar 08 '16 at 17:15
2

If you use numpy, you can easily create 2d arrays:

import numpy as np

row = 3
col = 5
num = 10
x = np.full((row, col), num)

x

array([[10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10],
       [10, 10, 10, 10, 10]])
  • Given the just *lousy* behavior of python's `[[0]*M]*N` which creates the "trap" described by @JasonChan - yes let's use `numpy` (which is really the primary reason to use python anyways) – WestCoastProjects Mar 06 '21 at 16:41
2
row=5
col=5
[[x]*col for x in [b for b in range(row)]]

The above will give you a 5x5 2D array

[[0, 0, 0, 0, 0],
 [1, 1, 1, 1, 1],
 [2, 2, 2, 2, 2],
 [3, 3, 3, 3, 3],
 [4, 4, 4, 4, 4]]

It is using nested list comprehension. Breakdown as below:

[[x]*col for x in [b for b in range(row)]]

[x]*col --> final expression that is evaluated
for x in --> x will be the value provided by the iterator
[b for b in range(row)]] --> Iterator.

[b for b in range(row)]] this will evaluate to [0,1,2,3,4] since row=5
so now it simplifies to

[[x]*col for x in [0,1,2,3,4]]

This will evaluate to [[0]*5 for x in [0,1,2,3,4]] --> with x=0 1st iteration
[[1]*5 for x in [0,1,2,3,4]] --> with x=1 2nd iteration
[[2]*5 for x in [0,1,2,3,4]] --> with x=2 3rd iteration
[[3]*5 for x in [0,1,2,3,4]] --> with x=3 4th iteration
[[4]*5 for x in [0,1,2,3,4]] --> with x=4 5th iteration

Satya
  • 21
  • 2
1

As @Arnab and @Mike pointed out, an array is not a list. Few differences are 1) arrays are fixed size during initialization 2) arrays normally support lesser operations than a list.

Maybe an overkill in most cases, but here is a basic 2d array implementation that leverages hardware array implementation using python ctypes(c libraries)

import ctypes
class Array:
    def __init__(self,size,foo): #foo is the initial value
        self._size = size
        ArrayType = ctypes.py_object * size
        self._array = ArrayType()
        for i in range(size):
            self._array[i] = foo
    def __getitem__(self,index):
        return self._array[index]
    def __setitem__(self,index,value):
        self._array[index] = value
    def __len__(self):
        return self._size

class TwoDArray:
    def __init__(self,columns,rows,foo):
        self._2dArray = Array(rows,foo)
        for i in range(rows):
            self._2dArray[i] = Array(columns,foo)

    def numRows(self):
        return len(self._2dArray)
    def numCols(self):
        return len((self._2dArray)[0])
    def __getitem__(self,indexTuple):
        row = indexTuple[0]
        col = indexTuple[1]
        assert row >= 0 and row < self.numRows() \
               and col >=0 and col < self.numCols(),\
               "Array script out of range"
        return ((self._2dArray)[row])[col]

if(__name__ == "__main__"):
    twodArray = TwoDArray(4,5,5)#sample input
    print(twodArray[2,3])
Antony Thomas
  • 3,576
  • 2
  • 34
  • 40
1

An empty 2D matrix may be initialized in the following manner:

temp=[[],[]]

Rashid Kamal
  • 131
  • 1
  • 3
0

This is the best I've found for teaching new programmers, and without using additional libraries. I'd like something better though.

def initialize_twodlist(value):
    list=[]
    for row in range(10):
        list.append([value]*10)
    return list
Paul Vincent Craven
  • 2,027
  • 3
  • 19
  • 24
0

Here is an easier way :

import numpy as np
twoD = np.array([[]*m]*n)

For initializing all cells with any 'x' value use :

twoD = np.array([[x]*m]*n
0

Often I use this approach for initializing a 2-dimensional array

n=[[int(x) for x in input().split()] for i in range(int(input())]

0

The general pattern to add dimensions could be drawn from this series:

x = 0
mat1 = []
for i in range(3):
    mat1.append(x)
    x+=1
print(mat1)


x=0
mat2 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp.append(x)
        x+=1
    mat2.append(tmp)

print(mat2)


x=0
mat3 = []
for i in range(3):
    tmp = []
    for j in range(4):
        tmp2 = []
        for k in range(5):
            tmp2.append(x)
            x+=1
        tmp.append(tmp2)
    mat3.append(tmp)

print(mat3)
juanfal
  • 11
  • 3
  • Welcome to SO. This question already has a massively up-voted accepted answer. At first sight, this post doesn't actually answer the question. See https://stackoverflow.com/help/how-to-answer for guidance. – Nick Jul 16 '18 at 16:53
0

The important thing I understood is: While initializing an array(in any dimension) We should give a default value to all the positions of array. Then only initialization completes. After that, we can change or receive new values to any position of the array. The below code worked for me perfectly

N=7
F=2

#INITIALIZATION of 7 x 2 array with deafult value as 0
ar=[[0]*F for x in range(N)]

#RECEIVING NEW VALUES TO THE INITIALIZED ARRAY
for i in range(N):
    for j in range(F):
        ar[i][j]=int(input())
print(ar)

0
lst=[[0]*n]*m
np.array(lst)

initialize all matrix m=rows and n=columns

0

Another way is to use a dictionary to hold a two-dimensional array.

twoD = {}
twoD[0,0] = 0
print(twoD[0,0]) # ===> prints 0

This just can hold any 1D, 2D values and to initialize this to 0 or any other int value, use collections.

import collections
twoD = collections.defaultdict(int)
print(twoD[0,0]) # ==> prints 0
twoD[1,1] = 1
print(twoD[1,1]) # ==> prints 1
Tej91
  • 131
  • 1
  • 2
  • 8
-5
from random import randint
l = []

for i in range(10):
    k=[]
    for j in range(10):
        a= randint(1,100)
        k.append(a)

    l.append(k)




print(l)
print(max(l[2]))

b = []
for i in range(10):
    a = l[i][5]
    b.append(a)

print(min(b))
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • 4
    Please add some text describing what your code does. – whackamadoodle3000 Oct 19 '17 at 22:53
  • 1
    Usually it's better to explain a solution instead of just posting some rows of anonymous code. You can read [How do I write a good answer](https://stackoverflow.com/help/how-to-answer), and also [Explaining entirely code-based answers](https://meta.stackexchange.com/questions/114762/explaining-entirely-%E2%80%8C%E2%80%8Bcode-based-answers). – Massimiliano Kraus Oct 19 '17 at 23:09