educative.io

Data Science for Non Programmers

names = [‘John Snow’,‘Ned Stark’,‘Bran Stark’,‘Jamie Lannister’,‘Sam Tarly’]

print(names[len(names)-1])

For these lines of code, why was the output “Sam Tarly”? Isn’t “len” looking for length? I thought the output would be the length of “Sam Tarly”


Type your question above this line.

Course: https://www.educative.io/collection/10370001/4733468011397120
Lesson: https://www.educative.io/collection/page/10370001/4733468011397120/5636263199637504

The len() method returns the total number of elements in an iterable object (i.e., a list in our case). As a result, we’ll get five 5 while subtracting one 1 from it, giving us four 5 -1 = 4, and accessing the item at index = 4 from the names list, gives us “Sam Tarly.” Alternatively, you might click on this link to learn more about accessing an element from a list.

Happy learning at Educative