404

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?

5
  • 12
    Just a small (or significant, depending on who is watching) nitpick : lists are not arrays. If you want arrays, use numpy. Commented Apr 22, 2012 at 1:10
  • This question is similar: it discusses the initialization of multidimensional arrays in Python. Commented Apr 6, 2013 at 3:35
  • @ArnabDatta How would you initialize a multidimensional array in numpy, then? Commented Apr 6, 2013 at 16:17
  • 1
    @AndersonGreen docs.scipy.org/doc/numpy/user/… Commented Apr 9, 2013 at 7:18
  • 1
    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 docs.scipy.org/doc/numpy-1.10.1/user/basics.creation.html Commented May 16, 2016 at 21:08

31 Answers 31

1
2
-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))
Sign up to request clarification or add additional context in comments.

2 Comments

Please add some text describing what your code does.
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, and also Explaining entirely code-based answers.
1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.