Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.
I'm learning data structure and algorithms and i came across a question in the list section. i thought after i had understood python, i had understood list but a question was asked and i find myself finding it hard to understand how the list indexing works.
here's the sample code:
arr = [1, 2, 3, 4, 5, 6]
for i in range(1, 6):
arr[i - 1] = arr[i]
for i in range(0, 6):
print(arr[i], end = " ")
it looks simple to understand but, i just can't understand it.
Basically, the purpose of this code is to break up strings that have camelCases into different strings, and I looked up some code samples online, and I found this solution. The code works, however, I don't quite understand what some of the syntax actually does, even after some research. I made a # comment on each line I didn't understand, explaining my confusion.
I simply just don't want to mindlessly copy code off the internet without understanding what it does!
Also, if possible, are there any lessons online you recommend I goto to learn about this concept to avoid further confusion? Thanks!
def camelCase(str):
words = [[str[0]]]
for c in str[1: ]: #What does str[1: ] do? I tried looking it up but Google isn't helpful
if words[-1][-1].islower() and c.isupper(): #I'm not quite sure what function [-1][-1] plays in this function
words.append(list(c))
else:
words[-1].append(c) #I once again don't understand the function of [-1] in this else statement
return [' '.join(word) for word in words]
Today I was learning lists in python and I came across an easy way to find the last element of a list, which is using the index -1, and I was wondering why is it so? could it be random or there is a specific reason for it?