Can a list variable contain another list?



Can a list variable contain items which are also lists of data?


In Python, a list can contain other lists in addition to more common data types such as strings, integers, and floating point values. Having a list which contains lists is useful when trying to represent a two-dimensional array. A good example of this type of structure is a game board. When used in this scenario, the main list contains other lists which each represent one row of the board. The items in the inside lists represent the columns of the board.

In the example below, a list is used to represent a game board for Tic-Tac-Toe. The associated code will print the board. In this example, the print() function for Python 3 is used which allows for the option end that prints without starting a new line.

tictactoe = [ ['X', 'O', 'X'],
              [ 'O', ' ', 'X'],

for row in tictactoe:
    for column in row:
        print(column + " ", end='')