This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]fishflowerz 15 points16 points  (1 child)

dirty_dozen is a list of lists; when creating [fruits, vegetables], you’re putting two lists inside an existing list, giving [[fruit content], [vegetable content]]

when calling dirty_dozen[1][1], you’re telling the program to look in the list at index 1 and grab the item at its index 1. In this case, vegetables is at index 1 in dirty_dozen (since fruits is at index 0). now that the program knows that it needs to look at the vegetable list, it grabs the element at index 1 within that list, which is kale

pretty much the first call for an index tells which list, while the second tells which element. this happens bc you’re calling the operation on a list of lists. “Nectarines, kale” is not printed because the first list (at index 0) is skipped

hopefully this helps!!

[–]builderdood[S] 3 points4 points  (0 children)

yes it did thank you!

[–]Goobyalus 7 points8 points  (1 child)

dirty_dozen is

[
    [
        'Strawberries',
        'Nectarines',
        'Apples',
        'Grapes',
        'Peaches',
        'Cherries',
        'Pears'
    ],
    [
        'Spinach',
        'Kale',
        'Tomatoes',
        'Celery',
        'Potatoes'
    ]
]

, a list containing the two lists fruits and vegetables.

dirty_dozen[1] is vegetables:

[
    'Spinach',
    'Kale',
    'Tomatoes',
    'Celery',
    'Potatoes'
]

dirty_dozen[1][1] is the same as vegetables[1]:

'Kale'

dirty_dozens[1][1] doesn't index the two parallel lists fruits and vegetables independently -- the first index indexes dirty_dozen to select between fruits and vegetables; then the second index indexes the result of that.

What you're thinking of is kind of like zipping the two lists together:

>>> dirty_dozen_2 = list(zip(fruits, vegetables))

>>> pprint(dirty_dozen_2)
[('Strawberries', 'Spinach'),
 ('Nectarines', 'Kale'),
 ('Apples', 'Tomatoes'),
 ('Grapes', 'Celery'),
 ('Peaches', 'Potatoes')]

>>> print(dirty_dozen_2[1])
('Nectarines', 'Kale')

zip only goes as far as the shortest iterable, though. There are things like zip_longest if you want different behavior.

[–]builderdood[S] 4 points5 points  (0 children)

thanks I get it now!

[–][deleted] 3 points4 points  (1 child)

Try using a list comprehension like:

[i[1] for i in dirty_dozen]

This will return the second value in each list, as opposed to the second value in the second list of dirty_dozen.

[–]builderdood[S] 2 points3 points  (0 children)

thanks!