🌐
Reddit
reddit.com › r/learnpython › what's the meaning and purpose of [-1] in this function?
r/learnpython on Reddit: What's the meaning and purpose of [-1] in this function?
February 29, 2024 -

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]

Top answer
1 of 4
14
Well, let's break it down! words = [[str[0]]] This is written somewhat strangely, but basically it is setting the words variable to a list containing the first character of the string (note: this code should not use str as a variable name as this is also a type). for c in str[1:]: This for loop is going over the rest of the string character by character. This is called a slice, and essentially it cuts the list into index values. For example, if you had a list [1, 2, 3, 4, 5] and you indexed it with [2:3], the list you'd get back is [3, 4]. This is because you are slicing from index 2 (the third item since indexes start at 0) to index 3 (the 4th item). If you did [2:] instead, your list would be [3, 4, 5], as the empty value means "to the end of the list." If you reversed it with [:2] you'd instead get a list of [1, 2] because you are slicing from 0 (start) to 2. Note that [:2] and [0:2] are functionally the same. In the next section, you have words[-1][-1]. An index of [-1] means "the last element (length - 1). Any time you have a negative index in Python, it means "that many from the length." NOTE: a slice at the end must be blank if you want the last character. If you did [2:] and [2:-1] you'd get different values...in this case [3, 4, 5] and [3, 4] respectively. So what does the words[-1][-1] actually do? Well, remember that words is a list of characters. So you are looking at the last string and last letter of that string, then checking if it is lower case. The if also checks if the next letter is upper case. If it is, we append a new list of characters to the end of the words list. If not, we are instead appending the current character to the current list. This is repeated for the whole string. This list of lists is then converted into a list of individual strings by combining the internal lists into strings instead of a list of characters. You can tell what's going on if you put a print statement before the return. If I had a string, say, testWordOutput, the list before the returning list comprehension looks like this: [['t', 'e', 's', 't'], ['W', 'o', 'r', 'd'], ['O', 'u', 't', 'p', 'u', 't']]. This is actually a somewhat overcomplicated way to do this. You can skip the entire part where you create the internal lists, for example this code: def split_camel_case(original): if not original: # Early return for empty string return [] words = [original[0]] # Start with the first character for char in original[1:]: # If the current character is uppercase and # the previous character is lowercase, # start a new word if char.isupper() and words[-1][-1].islower(): words.append(char) else: # Otherwise, append the current character to the last word words[-1] += char return words This code does the exact same thing but is perhaps a bit more clear in how it works. It still has many of the same elements (the basic concept wasn't wrong) but removes the need for a list comprehension. Hopefully that makes sense, please let me know if you have questions.
2 of 4
11
You should experiment with code in the Python shell, that way you can try these things and see what they do.
Python slicing, a[len(a)-1:-1:-1] May 9, 2025
r/learnpython
last yr.
What does this mean: s[::-1] == s ? Apr 5, 2012
r/learnpython
14y ago
What's the difference between [:-1] and [::-1] in Python? Feb 21, 2022
r/learnprogramming
4y ago
Why does [::-1] reverse a list? Mar 12, 2022
r/learnpython
4y ago
More results from reddit.com
🌐
Purple Frog Systems
purplefrogsystems.com › home › python lists – what do i need to know?
Python Lists – What do I need to know? - Purple Frog Systems
July 22, 2025 - Access elements of a list using list[index]. Indexing in Python starts at 0, which means that the first element has an index of 0.
Discussions

Why does Python start at index -1 (as opposed to 0) when indexing a list from the end? - Stack Overflow
For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12. In Python, though, arrays are more often used as linear data structures than circular ones, so indices larger than -1 + len(xs) or smaller than -len(xs) are out of bounds since ... More on stackoverflow.com
🌐 stackoverflow.com
Why is the index -1 always denoted as the last element of a list in python?
You can count backwards from the end like this. -1 is the last item, and -2 is the second to last item, etc. More on reddit.com
🌐 r/learnpython
7
1
February 25, 2022
python - Negative list index? - Stack Overflow
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. More on stackoverflow.com
🌐 stackoverflow.com
Embarrassingly, i don't understand how list indexing works
Let us step back a little. Before understanding your example, try to grok the example below for i in range(0, 3): print(i) which results in: 0 1 2 And the example below my_list = [42, 6, 2024] for i in range(0, 3): print(i, my_list[i]) Which results in: 0 42 1 6 2 2024 Are those clear to ya? Thanks! More on reddit.com
🌐 r/learnpython
26
15
August 31, 2024
🌐
ReqBin
reqbin.com › code › python › h54arbqc › python-list-index-example
How do I find the index of an element in a Python list?
In Python, list indexes start at 0. You can also check if an element exists in a list using the "in" operator. In this Python List Index example, we get the index of a list item using the list.index() method.
🌐
HackerEarth
hackerearth.com › practice › notes › samarthbhargav › a-quick-intro-to-indexing-in-python
A Quick intro to Indexing in Python - Samarth Bhargav
To access elements in a list, you can use the square bracket notation. There are many methods to access elements in python. python lists are 0-indexed. So the first element is 0, second is 1, so on.
🌐
Quansight-labs
quansight-labs.github.io › ndindex › indexing-guide › index.html
Guide to NumPy Indexing - ndindex documentation
These indices will not work on the built-in Python sequence types like list and str; they are only defined for NumPy arrays. This section is itself split into six subsections. First is a basic introduction to what a NumPy array is. Following this are pages for each of the remaining index types, the basic indices: tuples, ellipses, and newaxis; and the advanced indices: integer arrays and boolean arrays (i.e., masks).
🌐
Python Guides
pythonguides.com › python-array-index-1
How To Use Python Array Index -1?
March 19, 2025 - Negative indexing is useful in Python lists. It will allow you to access elements from the end of the list. While positive indices start from 0, negative indices start from -1, where -1 refers to the last element of the collection, -2 to the second last, and so on.
🌐
Mimo
mimo.org › glossary › python › index-element
Python Index: Efficient Data Retrieval and Navigation
Python also supports negative indices. A negative index counts from the end of the sequence: ... Get a particular item from a list, tuple, or string using its position. ... Change values in a list by assigning a new value to a specific index.
Top answer
1 of 7
186

To explain it in another way, because -0 is equal to 0, if backward starts from 0, it is ambiguous to the interpreter.


If you are confused about -, and looking for another way to index backwards more understandably, you can try ~, it is a mirror of forward:

arr = ["a", "b", "c", "d"]
print(arr[~0])   # d
print(arr[~1])   # c

The typical usages for ~ are like "swap mirror node" or "find median in a sort list":

"""swap mirror node"""
def reverse(arr: List[int]) -> None:
    for i in range(len(arr) // 2):
        arr[i], arr[~i] = arr[~i], arr[i]

"""find median in a sort list"""
def median(arr: List[float]) -> float:
    mid = len(arr) // 2
    return (arr[mid] + arr[~mid]) / 2

"""deal with mirror pairs"""
# verify the number is strobogrammatic, strobogrammatic number looks the same when rotated 180 degrees
def is_strobogrammatic(num: str) -> bool:
    return all(num[i] + num[~i] in '696 00 11 88' for i in range(len(num) // 2 + 1))

~ actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.


Discussion about whether should use python tricks like ~:

In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.

For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.

# a strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down)
# find all strobogrammatic numbers that are of length = n
def findStrobogrammatic(self, n):
    nums = n % 2 * list('018') or ['']
    while n > 1:
        n -= 2
        # n < 2 is so genius here
        nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
    return nums

I have summarized python tricks like this, in case you are interested.

2 of 7
175
list[-1]

Is short hand for:

list[len(list)-1]

The len(list) part is implicit. That's why the -1 is the last element. That goes for any negative index - the subtraction from len(list) is always implicit

Find elsewhere
🌐
Tutorialspoint
tutorialspoint.com › python › string_index.htm
Python String index() Method
If these two parameters are not specified, then the index() function works from the 0th index to the end of the string. If the substring is not found in the input string, it raises a ValueError unlike the find() function. In the following section, we will be learning more about this method. The following is the syntax for the python string index() method.
🌐
Quora
quora.com › Why-does-Python-start-at-index-1-when-iterating-an-array-backwards
Why does Python start at index 1 when iterating an array backwards? - Quora
I don't know exactly why Guido van Rossum designed Python start at index -1 when iterating an array backward, but I would like to think of negative index like this. I think it makes much sense if we see the list as a circle. Let’s say we have a list of size 6 then the list has index [0, 1, 2, 3, 4, 5] if we move in ...
🌐
O'Reilly
oreilly.com › library › view › learn-programming-in › 9781789531947 › 6f7c08e0-e72b-402b-86fe-843ac3a8aa7e.xhtml
Indexing and slicing strings - Learn Programming in Python with Cody Jackson [Book]
November 29, 2018 - Python strings functionally operate the same as Python lists, which are basically C arrays (see the Lists section). Unlike C arrays, characters within a string can be accessed both forward and backward. Frontward, a string starts off with a position of 0 and the character desired is found through an offset value (how far to move from the beginning of the string).
Author: Cody Jackson
Published: 2018
Pages: 304
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › index in python
Index Function in Python: Complete Guide
May 28, 2025 - Negative indexing provides convenient access to end elements. You don't need to calculate list length for accessing. The last element is always at index -1. Negative index in Python eliminates length calculations completely.
🌐
Roberto Reif
robertoreif.com › blog › 2025 › 7 › 8 › python-lists-index
PYTHON LISTS: Index — Roberto Reif
October 25, 2025 - To do this, use the index method, passing the desired item as an argument. This method returns the index position of the element within the list. What other Python questions do you have
🌐
Python
docs.python.org › 3.4 › genindex.html
Index — Python 3.4.10 documentation
February 4, 2018 - index · modules | Python » · 3.4.10 Documentation » · © Copyright 1990-2019, Python Software Foundation. The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Jun 16, 2019. Found a bug? Created using Sphinx 1.2.3.
🌐
Real Python
realpython.com › lessons › using-indices
Using Indices (Video) – Real Python
In this lesson, you’ll be looking at the books dataset indices, how to use them, and how to work with them. Indices, then. You usually want something to refer to the rows, something unique with which you can refer to each row, something like an…
Published: May 31, 2022
🌐
O'Reilly
oreilly.com › library › view › pandas-for-everyone › 9780134547046 › app12.xhtml
L. Slicing Values - Pandas for Everyone: Python Data Analysis, First Edition [Book]
December 15, 2017 - L. Slicing Values Python is a zero-indexed language (things start counting from zero), and is also left inclusive, right exclusive you are when specifying a range of values. This...
Author: Daniel Y. Chen
Published: 2017
Pages: 410
🌐
Railsware
railsware.com › home › engineering › indexing and slicing for lists, tuples, strings, other sequential types in python
Python Indexing and Slicing for Lists, Tuples, Strings, other Sequential Types | Railsware Blog
January 22, 2025 - In negative indexing system -1 corresponds to the last element of the list(value ‘black’), -2 to the penultimate (value ‘white’), and so on.
🌐
Learnlearn
revise.learnlearn.uk › app › section › 2053 › 613
List Indexing Basics
Accessing list elements is a fundamental concept in programming that involves retrieving values stored in a list using their index. In programming languages like Python, lists are indexed starting from 0, meaning the first element has an index of 0.