Python Indexing, Slicing & SortingGet Certified
What Are Indexing and Slicing?
Every item in a sequence (list, tuple, or string) has a position called an index. Python starts counting at 0, so the first item is at index 0, the second at index 1, and so on. You can also count from the end with negative indexes: -1 is the last item, -2 is the second-to-last, and so on.
Slicing lets you pull out a continuous section of a sequence. The basic form is sequence[start:stop]. The slice includes the item at start but stops before the item at stop. You can also add a step: sequence[start:stop:step].
These tools are useful whenever a program needs to inspect a particular value or work with only part of a larger collection. You can use the same approach with lists, tuples, and strings because each is an ordered sequence. Understanding how positions relate to the stored values makes it easier to select data accurately and avoid common boundary mistakes.
- Positive index: counts from the left, starting at 0.
- Negative index: counts from the right, starting at β1.
- Slice:
[start:stop]returns a new sequence containing items from start up to (but not including) stop. - Step:
[start:stop:step]can skip items or reverse the order. - Original is safe: indexing and slicing never change the original sequence unless you assign back into it.
- Out of range: asking for a single index that does not exist raises
IndexError. A slice that goes past the end simply returns what is available.
Positive and Negative Indexing
The safest way to learn indexes is to print them side by side with the values. Once you see the pattern, negative indexes become natural for grabbing the last few items without calculating the length. Think of an index as an address for one specific element, not as a count of items.
Positive positions are especially useful when you know where an item appears near the beginning of a sequence. Negative positions are convenient when the sequence may change in length but you still need its final entries. Try changing the list and checking how the same index selects a different value.
Try It: City Rankings and Last Items
Click Test My Code. Then change the list of cities or try a different negative index.
cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
print(cities[0])
print(cities[2])
print(cities[-1])
print(cities[-2])
print(len(cities))len() returns 5, which is useful when you need the exact size.Basic Slicing
A slice creates a brand-new list or string. The original stays untouched. Leaving out start means βfrom the beginning.β Leaving out stop means βall the way to the end.β
Use slicing when you need a section for a calculation, display, or follow-up operation without rebuilding the sequence manually. The start and stop positions can be adjusted to select different ranges, while omitted values make common beginning-to-end selections shorter to write. Remember that the selected range follows the order of the original sequence.
Try It: Extract Parts of a Roster
Click Test My Code. Then try different start and stop values.
roster = ["Ava", "Liam", "Mia", "Noah", "Emma", "Jackson", "Olivia"]
first_three = roster[0:3]
print(first_three)
middle = roster[2:5]
print(middle)
from_third = roster[2:]
print(from_third)
last_two = roster[-2:]
print(last_two)[0:3] starts at index 0 and stops before index 3, giving Ava, Liam, Mia.[2:5] grabs indices 2, 3, and 4: Mia, Noah, Emma.[-2:] is a clean way to take the final two items.Slicing Strings
Strings are sequences of characters, so the same indexing and slicing rules apply. This is especially handy for cleaning or extracting parts of text such as ZIP codes, phone numbers, or state abbreviations.
Each letter, digit, punctuation mark, and space occupies a position, so even a comma or blank space affects the index of the characters that follow it. Before choosing slice boundaries, inspect the text carefully or print individual characters with their positions. For more flexible text processing, methods such as split() may be easier when the parts are separated by a known delimiter.
Try It: Work with a U.S. Address Line
Click Test My Code. Then try slicing a different part of the address.
address = "742 Evergreen Terrace, Springfield, IL 62704"
street_num = address[0:3]
print(street_num)
city = address[23:34]
print(city)
state = address[36:38]
print(state)
zip_code = address[-5:]
print(zip_code)
print(address[::-1])[-5:] grabs the last five characters, which are the ZIP code.Slices with a Step
The third number in a slice is the step. A step of 2 takes every other item. A negative step walks the sequence backward. This is the cleanest way to reverse a list or string.
The step controls the direction and spacing between selected positions, so it can be useful for sampling regularly spaced values from a larger sequence. A positive step moves forward, while a negative step moves backward. When using a negative step with explicit boundaries, make sure the starting position is located after the stopping position in the sequence.
Try It: Every Other Score and Reversals
Click Test My Code. Then change the step value or try a different range.
scores = [88, 92, 75, 96, 81, 90, 67]
every_other = scores[::2]
print(every_other)
temps = [32, 45, 58, 71, 84]
reversed_temps = temps[::-1]
print(reversed_temps)
motto = "E Pluribus Unum"
print(motto[::-1])
print(scores[1:6:2])[::2] starts at the beginning, goes to the end, and steps by 2.[::-1] is the standard Python idiom for reversing any sequence.[1:6:2] starts at index 1, stops before 6, and takes every second item.Sorting with sort() and sorted()
Python gives you two main tools for putting items in order. The list method .sort() rearranges the list in place and returns None. The built-in function sorted() returns a brand-new sorted list and leaves the original alone. Both accept a reverse=True argument and a key function for custom ordering.
Choose between them based on what should happen to the original data after sorting. If later code still needs the items in their original order, keep that sequence unchanged and work with the result from sorted(). If changing the existing list is intentional, .sort() is a direct option and avoids keeping a separate sorted copy.
Try It: Sort Prices and Names
Click Test My Code. Then try sorting in reverse or adding another name.
sort() and sorted().prices = [12.99, 4.50, 8.75, 19.99, 3.25]
prices.sort()
print(prices)
names = ["Sophia", "Liam", "Olivia", "Noah", "Emma"]
alphabetical = sorted(names)
print(alphabetical)
print(names)
descending = sorted(prices, reverse=True)
print(descending).sort() changes the original list permanently and returns None.sorted() builds a fresh list and leaves the original untouched.reverse=True produces the prices from largest to smallest.Sorting with a Key Function
When the default alphabetical or numeric order is not what you need, pass a key function. The function is called once for every item and the return value is used for comparison. Common keys are len, str.lower, or a small lambda.
A key function lets you sort complex-looking records by one meaningful property without changing the original items. For example, names can be ordered by length, case-insensitive text, or a particular word, while numeric records can be ranked by a score. Keep the key expression focused on the value that should determine the order.
Try It: Sort by Length and by Last Name
Click Test My Code. Then try sorting the cities by the length of their names.
cities = ["Austin", "Denver", "Seattle", "Miami", "Boston"]
by_length = sorted(cities, key=len)
print(by_length)
full_names = ["Emma Thompson", "Liam Garcia", "Olivia Brown", "Noah Martinez"]
by_last = sorted(full_names, key=lambda name: name.split()[-1])
print(by_last)
print(sorted(cities, key=len, reverse=True))key=len tells Python to compare the length of each string instead of the string itself.reverse=True puts the longest city names at the front.Combining Slicing and Sorting
Real programs often need both operations together: take a slice of recent data, then sort that slice. Because slicing returns a new list, you can sort the copy without touching the original records.
The order of the operations matters because it changes which items are included in the final result. Slicing first is useful when you only want to analyze a selected group, such as the latest entries. Sorting first is better when you want the highest or lowest values from the entire collection, after which a short slice can keep only the required number of results.
Try It: Recent High Scores
Click Test My Code. Then change how many recent scores you keep.
game_scores = [14, 21, 9, 28, 17, 32, 25, 19]
recent = game_scores[-4:]
print(recent)
recent_sorted = sorted(recent, reverse=True)
print(recent_sorted)
top_three = sorted(game_scores, reverse=True)[:3]
print(top_three)[-4:] is a clean way to take the most recent entries.Practical Example: Cleaning and Ordering Student Data
Putting indexing, slicing, and sorting together lets you clean messy data quickly. The following example works with a short list of student records that might come from a school spreadsheet.
In practical data tasks, information often arrives as text that needs to be separated, checked, and arranged before it can be used. Small operations can turn those raw entries into useful fields, such as a student’s last name or numeric grade. Once the values are extracted, filtering and ordering help reveal the records that matter most.
Try It: Clean and Rank Students
Click Test My Code. Then add another student or change the grade cutoff.
students = ["Liam Garcia: 92", "Emma Thompson: 78", "Noah Martinez: 88", "Olivia Brown: 95", "Sophia Lee: 81"]
last_names = [s.split()[1].rstrip(":") for s in students]
print(sorted(last_names))
high_achievers = [s for s in students if int(s.split(": ")[1]) >= 85]
print(sorted(high_achievers, key=lambda s: int(s.split(": ")[1]), reverse=True))
top_two = sorted(students, key=lambda s: int(s.split(": ")[1]), reverse=True)[:2]
print(top_two)Tip: When a slice or sort expression starts to look crowded, assign intermediate results to clear variable names. Readable code is easier to debug than a single long line.
Common Mistakes with Indexing, Slicing & Sorting
Most problems in this topic come from selecting the wrong boundary, expecting an operation to change data when it does not, or confusing the result returned by a method. These issues are easier to catch when you test a small example and inspect the value after each operation. Pay particular attention to empty sequences and indexes near either end.
- Off-by-one errors: Remember that the stop index is exclusive.
list[0:3]gives three items (indexes 0, 1, 2), not four. - IndexError on a single index:
list[10]raises an error if the list has fewer than 11 items. A slice that goes past the end simply returns a shorter result. - Forgetting that sort() returns None: Writing
new = my_list.sort()stores None. Usesorted(my_list)when you need a new list. - Mutating while iterating: Changing a list with
.sort()or slice assignment while a loop is running over it can produce surprising results. - Assuming strings are mutable: You cannot assign to a slice of a string. Strings are immutable; create a new string instead.
- Confusing key and reverse:
keycontrols how items are compared;reverseonly flips the final order. - Negative step without care:
list[3:1:-1]works, but the start must be higher than the stop when the step is negative.
Good Habits for Indexing, Slicing & Sorting
Clear sequence operations make programs easier to understand, maintain, and debug. Prefer expressions that communicate what part of the data you need, and use descriptive variables when a selection will be reused. A few quick checks with short or empty collections can also prevent assumptions from becoming bugs when real data changes.
- Prefer negative indexes when you only care about the end of a sequence.
- Use clear variable names for slices:
recent_scores = scores[-5:]is easier to read later than a bare slice. - Choose
sorted()when you need to keep the original list; use.sort()only when you intentionally want to change it. - Pass a
keyfunction instead of writing a complicated comparison yourself. - When you need both a filter and a sort, filter first (often with a comprehension) and then sort the smaller list.
- Test edge cases: empty lists, single-item lists, and slices that go past the end.
Key Takeaways
Indexing, slicing, and sorting are practical ways to access and organize ordered data in Python. Each operation serves a different purpose: selecting one element, creating a portion of a sequence, or arranging items by a chosen rule. Together, they provide a flexible foundation for working with lists and text in everyday programs.
- Indexes start at 0. Negative indexes count from the end (β1 is the last item).
- A slice
[start:stop]includes start and excludes stop. An optional step can skip items or reverse the sequence. .sort()changes a list in place;sorted()returns a new sorted list.- Both sorting tools accept
reverse=Trueand akeyfunction for custom order. - Slicing and sorting work on any sequence: lists, tuples, and strings.
- Combine slicing and sorting to work with recent data or top-N results cleanly.
- When an expression becomes hard to read, break it into named steps.
Frequently Asked Questions
The answers below address common questions that arise when selecting sequence elements, choosing slice boundaries, reversing data, and sorting collections. If a result looks unexpected, test the operation with a short example and check the original sequence as well as the returned value. This makes it easier to identify whether the issue is an index, a boundary, or a sorting choice.
What is the difference between indexing and slicing in Python?
Indexing retrieves a single item with list[i]. Slicing retrieves a continuous section with list[start:stop] and always returns a new sequence (list or string), even if the section contains only one item.
Why does my slice stop one item earlier than I expected?
The stop index is exclusive. list[0:3] returns the items at positions 0, 1, and 2. To include the item at index 3 you must write list[0:4].
How do I reverse a list or string in Python?
The cleanest way is the slice with a step of β1: my_list[::-1] or my_string[::-1]. This creates a new reversed sequence and leaves the original unchanged.
When should I use list.sort() versus sorted()?
Use list.sort() when you want to rearrange the existing list and do not need the original order. Use sorted() when you need a new sorted list and want to keep the original intact.
How can I sort a list of strings by length?
Pass key=len to sorted() or to the sort() method: sorted(names, key=len). The function len is called once for each string and the returned lengths are used for comparison.
What happens if I ask for an index that is too large?
A single index that is out of range raises IndexError. A slice that goes past the end of the sequence simply returns all available items and does not raise an error.
Can I sort a list of dictionaries or custom objects?
Yes. Supply a key function that extracts the value you want to compare, for example key=lambda d: d[“score”] or key=lambda student: student.gpa.
Is slicing a list expensive?
Slicing creates a shallow copy of the selected portion. For ordinary lists of numbers or strings the cost is negligible. For very large lists you may prefer indexes or generators when you only need to examine items one at a time.