Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I am new to python. I am working on a 2d list, this is my code:

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 = []

I am getting the results but I feel its a lengthy process. Is there any short cut?

1 Answer

0 votes
by (36.8k points)

This is the pattern which comes with Python:

bar = []

for item in some_iterable:

    bar.append(SOME EXPRESSION)

It helps in the introduction of list comprehension and also concerts to snippets.

bar = [SOME EXPRESSION for item in some_iterable]

This is shorter and clear.

The code follows the 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)                           /

If you are a beginner and want to know more about Data Science the do check out the Data Science course

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
asked Dec 30, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...