Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Julian Jaramillo
Julian Jaramillo
7,265 Points

Please explain what this line of code does. books[len(books) -1]

Hi!

In the Beginning Python track | Introducing Lists | Indexing video. At the 06:23 minute mark, Craig writes this line of code to show how you can run code inside a list.

books[len(books) -1]

I'm trying to understand what the code is asking. Can someone please explain what this line of code does?

Thanks in advance.

2 Answers

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

I'm not sure which video you are looking at, but what he appears to be doing is referencing the last item in the books list. Craig is showing you can access the last item of any list by referencing its length minus 1. len(books) - 1 and then I am showing you can also access the last element by using -1 index of a list.

I hope this makes it clear.

PS C:\Users\jeff> python
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> # Let's create a list of books
>>> books = ['The Cat in the Hat', 'Huckleberry Finn','Moby Dick']
>>>
>>> print('Length of the books list:')
Length of the books list:
>>> print(len(books))
3
>>>
>>> print('The first book: ')
The first book:
>>> print(books[0])
The Cat in the Hat
>>>
>>> print('The last book, given the length is 3:')
The last book, given the length is 3:
>>> print(books[2])
Moby Dick
>>>
>>> print('Another way to access the last book:')
Another way to access the last book:
>>> print(books[len(books)-1])
Moby Dick
>>>
>>> print('One other way to access the last book:')
One other way to access the last book:
>>> print(books[-1])
Moby Dick
>>>
>>> # but, we can add MORE books to the list and it still works
>>> print('Adding 2 books to the list')
Adding 2 books to the list
>>> books = books + ['Treehouse Cookbook', 'Little Women']
>>>
>>> print('Length of the books list:')
Length of the books list:
>>> print(len(books))
5
>>> print('Another way to access the last book:')
Another way to access the last book:
>>> print(books[len(books)-1])
Little Women
>>>
>>> print('One other way to access the last book:')
One other way to access the last book:
>>> print(books[-1])
Little Women
Julian Jaramillo
Julian Jaramillo
7,265 Points

Thank you for your help/time.