2D Lists

Remember: - Lists can be used to group different values together - it’s just a collection of things. - You can make a list in Python by putting different things in a box of brackets [] separated by commas:

Guess what? You can also make lists of lists!! These are called 2D lists in Python.

You can make a 2D list like this:

# list number 1
fruit = ['apple', 'banana', 'grape', 'mango']

# list number 2
veggies = ['lettuce','carrot','cucumber','beet']

# create 2D list
food = [fruit, veggies]

# print 2D list
print(food)
[['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet']]

What data type is food?

print(type(food))
<class 'list'>

What is the length of your list?

# print length of food
print(len(food))
2

Is this what you expected? Since food is a list that contains two list objects, the length of food is 2.

# make a list of meats and save it to the variable meat
meat = ['chicken','beef','fish','pork']
# add another list to food with meat
food.append(meat)

# print food
print(food)
[['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet'], ['chicken', 'beef', 'fish', 'pork']]

What is the length of food now?

print(len(food))
3

Make a variable called double_food that contains the food list twice. Print out double_food.

# create double_food that contains food twice
double_food = food + food

# print double_food
print(double_food)
[['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet'], ['chicken', 'beef', 'fish', 'pork'], ['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet'], ['chicken', 'beef', 'fish', 'pork']]

What is the length of double_food? Is this what you expected?

print(len(double_food))
6

You can also make 2D lists without assigning variables first:

# create a 2D list of numbers
numbers = [[1,2,3,4],[1,2,3],[1,2]]

# print 2D list of numbers
print(numbers)
[[1, 2, 3, 4], [1, 2, 3], [1, 2]]

What is the length of numbers?

# print length of numbers
print(len(numbers))
3

What happens if you add the food and numbers together?

print(food + numbers)
[['apple', 'banana', 'grape', 'mango'], ['lettuce', 'carrot', 'cucumber', 'beet'], ['chicken', 'beef', 'fish', 'pork'], [1, 2, 3, 4], [1, 2, 3], [1, 2]]

Nice job! You just learned how to make 2D lists in Python!