How to combine lists in Python 3

Lets start with 3 lists:

[ 'chicken', 'rice', 'ham' ]

[ 'Eggs', 'Spam', 'carrots' ]

[ 'tomato', 'cucumber', 'tuna' ]

We can nest the lists:

ingredients = [

  [ 'chicken', 'rice', 'ham' ],

  [ 'Eggs', 'Spam', 'carrots' ],

  [ 'tomato', 'cucumber', 'tuna' ]

]

This is called a two-dimensional list.

Extracting a nested list:

print(ingredients[0])

Would return the inner list at position 0:

'[ 'chicken', 'rice', 'ham' ]'

To extract an individual item from within a nested list we would first need to get the list:

print(ingredients[0][1])

This gives us ‘rice’, as we first access the inner list using its index (0), and then the item from within the list at position 1.

We can make this code more accessible by creating a dictionary and give each list a key:

ingredients = {

  'List one'   :  [ 'chicken', 'rice', 'ham' ],

  'List two'   :  [ 'Eggs', 'Spam', 'carrots' ],

  'List three' :  [ 'tomato', 'cucumber', 'tuna' ]

}

To get each list we would write:

print( ingredients['List one'] )

Which would return:

[ 'chicken', 'rice', 'ham' ]

And to get the actual item:

print( ingredients['List one'][1] )

Would return ‘rice’, which is at position 1 in ‘List one’.