Python | Lists within lists

A list can be nested within another list.

numberOne = 5
numberTwo = 6
numberThree = 7
numbers = [1, 2, 3, 4, [numberOne, numberTwo, numberThree], 8, 9]
print(numbers[0])
print(numbers[4])
print(numbers[6])

This would be the output in the terminal:

>>> numberOne = 5
>>> numberTwo = 6
>>> numberThree = 7
>>> numbers = [1, 2, 3, 4, [numberOne, numberTwo, numberThree], 8, 9]
>>> print(numbers[0])
1
>>> print(numbers[4])
[5, 6, 7]
>>> print(numbers[6])
9

Note:

  • Usually, a list will contain only items that are the same data type. But, that is usually, not always; You can include several different data types in a list.
  • Lists of lists are often used to represent 2D grids, as Python lacks the multidimensional arrays that would be used for this in other languages.
number = 3
just_a_list = [“strange”, 7, [number, 9], 4.50]
print(list_one[2])
print(list_one[3])
print(list_one[4])

And the terminal output will be:

>>> number = 3
>>> list_one = [1, 2, [number, 9], 4.50, "string", "strange"]
>>> print(list_one[2])
[3, 9]
>>> print(list_one[3])
4.5
>>> print(list_one[4])
string

Leave a Reply