Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a list in Python using the multiply operator

Recently in Python I have encountered this statement:

board.append([' '] * 8)

I have tried to search the Internet with Google to find some more information about this type of statement, but I can't.

I know what the statement does, but I do not understand how, in what manner is doing, that.

This is the first time I have seen the * operator used on a list. Can you please refer me to a place where I can find some more information about this type of statements?

like image 381
depecheSoul Avatar asked Feb 18 '23 03:02

depecheSoul


2 Answers

Can you please refer me to a place where I can find some more information about this type of statements.

Most of the relevant operators and methods are defined here: Sequence Types.

Specifically s * n is defined as

s * n, n * s -- n shallow copies of s concatenated

Here, s is a sequence and n is a number.

Thus, [' '] * 8 returns a list consisting of eight ' '.

board.append() appends the result to board, which presumably is a list (of lists).

like image 131
NPE Avatar answered Feb 20 '23 17:02

NPE


It works like this:

>>> L = [0]*10
>>> L
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> 

If you need to know how something works in Python, look it up in the Python documentation, or just experiment with it yourself.

like image 40
jackcogdill Avatar answered Feb 20 '23 17:02

jackcogdill