Skip to content
PythonAlgorithms and Capstone Practicebeginner30 min read

Searching and Sorting Basics

Learn linear search, membership checks, sorted(), list.sort(), custom sorting keys, and basic time complexity.

In this lesson, you will learn

  • ✓Explain what searching and sorting accomplish and distinguish between them.
  • ✓Implement linear search using a loop and return the index of a matching element.
  • ✓Use the in operator to check membership in a collection.
  • ✓Explain the difference between sorted() and list.sort().
  • ✓Sort numbers, strings, and records using the key and reverse parameters.
  • ✓Trace search and sorting examples and predict their outputs.
  • ✓Handle empty collections, missing values, and duplicate elements appropriately.
  • ✓Explain the basic time complexity of linear search and comparison-based sorting.

1. Searching and sorting: the basic idea

Searching means looking for a particular value or item in a collection. Depending on the problem, you may need to know whether the item exists, where it appears, or which record matches a condition.

Sorting means arranging the elements of a collection according to an ordering rule. Common examples include sorting integers from smallest to largest, names alphabetically, or records by their scores.

These operations solve different problems. Searching answers a question about a target value, while sorting changes the order in which data is presented or stored.

Python includes built-in tools such as the in operator, sorted(), and list.sort(). A manual linear search is also useful for learning how a search algorithm examines elements one by one.

Before selecting an approach, identify the required result. A membership check returns a Boolean value, a search function might return an index, and a sorting operation returns or modifies an ordered collection.

Check membership and sort a list

Check membership and sort a list
python
numbers = [8, 2, 5]
 
print(5 in numbers)
print(7 in numbers)
print(sorted(numbers))
Output
True False [2, 5, 8]

The expression 5 in numbers checks whether 5 is present and evaluates to True. The expression 7 in numbers evaluates to False because 7 is absent. sorted(numbers) produces a new list in ascending order. The original numbers list remains [8, 2, 5]. The membership checks and sorting operation answer different questions: existence and ordering.

Note

Always identify whether the task requires a Boolean result, an index, a matching item, or an ordered collection. Those results are not interchangeable.

2. Linear search: examine items one by one

Linear search, also called sequential search, checks collection elements one at a time until it finds the target or reaches the end.

For a list, begin with the first element. Compare it with the target. If the values match, return the current index. Otherwise, continue to the next element. If no element matches, report that the target was not found.

Python list indexes begin at zero. Therefore, the first element has index 0, the second has index 1, and the element at index i is accessed using items[i].

A search function needs a clearly defined result for failure. One common convention is to return -1 when the target is absent. This works for a function specifically designed to return a list index because -1 is not a valid non-negative index for a successful position in the list. However, Python itself uses -1 to access the last element, so callers must interpret the function's return value according to its documented contract.

Linear search does not require the list to be sorted. It can inspect an ordinary list in any order, which makes it a useful general-purpose approach for small or unsorted collections.

Implement linear search

Implement linear search
python
def linear_search(items, target):
for index in range(len(items)):
if items[index] == target:
return index
 
return -1
 
numbers = [8, 2, 5, 9]
 
print(linear_search(numbers, 5))
print(linear_search(numbers, 7))
Output
2 -1

range(len(items)) generates the valid indexes from 0 up to, but not including, the list length. At index 0, the value is 8. It does not match 5. At index 1, the value is 2. It does not match 5. At index 2, the value is 5. The function returns 2 immediately. When searching for 7, the function checks every element without finding a match, then returns -1. The function returns the first matching index if a value appears more than once.

Note

For a successful linear search, the number of comparisons depends on the target's position. A target at the first position needs one comparison; a target at the last position may require checking every element.

3. Searching with Python's in operator

If the only question is whether a value exists in a collection, Python's in operator is usually the clearest choice. It produces True when the item is found and False otherwise.

For lists and tuples, membership testing generally checks elements until a match is found or the collection is exhausted. For strings, membership checks whether a substring occurs in the string. For dictionaries, in checks keys, not values.

A membership check does not return the index of a matching list element. If you need an index, use an appropriate method such as list.index() when its first-match behavior fits the requirement, or implement a search function when you need custom logic.

The list.index() method raises ValueError when the requested value is absent. By contrast, in simply evaluates to False for a missing item.

Membership testing is not identical in performance across all data structures. List membership generally takes linear time in the worst case, while dictionary and set membership are typically O(1) on average under normal hashing assumptions.

Membership in a list and a dictionary

Membership in a list and a dictionary
python
fruits = ["apple", "mango", "orange"]
student = {"name": "Asha", "score": 90}
 
print("mango" in fruits)
print("grape" in fruits)
print("name" in student)
print("Asha" in student)
Output
True False True False

Mango is an element of the fruits list, so the first result is True. Grape is absent from the list, so the second result is False. The dictionary contains the key name, so the third result is True. Asha is a value, not a key, in the dictionary. The expression "Asha" in student therefore evaluates to False. To search dictionary values, use a check such as "Asha" in student.values().

Note

Use in for an existence check. Use a search method or custom function when the task requires a position or additional behavior.

4. Sort a collection with sorted()

The built-in sorted() function takes an iterable and returns a new list containing its elements in sorted order. For numbers, the default ordering is ascending.

Because sorted() creates a new list, it does not reorder the original list. This is useful when the original order must be preserved or when you need both the original and the sorted data.

The reverse parameter controls the direction. sorted(items, reverse=True) produces descending order according to the selected ordering rule.

sorted() accepts many iterable types, including lists, tuples, strings, and dictionary views. Its result is always a list. For example, sorting a tuple produces a list rather than another tuple.

By default, elements must be mutually orderable. Sorting a mixture of integers and strings generally raises TypeError in Python 3 because those values do not have a natural ordering comparison with each other.

Sort in ascending and descending order

Sort in ascending and descending order
python
numbers = [8, 2, 5, 1]
 
ascending = sorted(numbers)
descending = sorted(numbers, reverse=True)
 
print(ascending)
print(descending)
print(numbers)
Output
[1, 2, 5, 8] [8, 5, 2, 1] [8, 2, 5, 1]

sorted(numbers) creates a new ascending list. reverse=True requests descending order. The original list is unchanged because neither call modifies it in place. The original order remains available in numbers.

Note

Use sorted() when you need a new ordered list and want to preserve the original collection's order.

5. Sort a list in place with list.sort()

Lists have a sort() method that rearranges the elements of the existing list. Unlike sorted(), list.sort() modifies the list in place and returns None.

Use list.sort() when the list itself should be reordered and you do not need to preserve its original order. Use sorted() when you need a separate sorted list.

A common mistake is assigning the result of list.sort() back to the same variable. Because sort() returns None, an assignment such as numbers = numbers.sort() replaces the list reference with None.

Both sorted() and list.sort() accept key and reverse parameters. These options let you control how items are compared and whether the resulting order is ascending or descending.

Python's built-in sorting is stable: when two items have equal sort keys, their relative order from the input is preserved. This is useful when sorting records by one property after an earlier sort by another property.

Compare sorted() and list.sort()

Compare sorted() and list.sort()
python
values = [3, 1, 2]
ordered = sorted(values)
 
print(values)
print(ordered)
 
values.sort()
print(values)
Output
[3, 1, 2] [1, 2, 3] [1, 2, 3]

The first print displays the unchanged original list. The second print displays the new list returned by sorted(). Calling values.sort() then rearranges values itself. The sort() method returns None, so it is called as a statement rather than assigned to ordered.

Note

Remember the distinction: sorted(iterable) returns a new list, while list.sort() changes the existing list and returns None.

6. Custom sorting with the key parameter

Sometimes the natural ordering of an item is not the ordering your problem requires. For example, you might sort words by length, names without regard to capitalization, or student records by score.

The key parameter accepts a function that calculates a comparison key for each item. Python orders the items according to those key values while keeping the original items in the resulting collection.

For sorting words by length, key=len tells Python to use each word's length as its sort key. For case-insensitive alphabetical sorting, key=str.lower uses a lowercase version of each string for comparison.

A lambda expression can define a small key function inline. For example, key=lambda student: student["score"] extracts a student's score from a dictionary.

A key function should return values that can be compared with one another. If several items produce the same key, Python's stable sort preserves their relative order from the input.

Sort words by length

Sort words by length
python
words = ["banana", "fig", "apple", "kiwi"]
 
print(sorted(words, key=len))
Output
['fig', 'kiwi', 'apple', 'banana']

len is used as the key function, so the sorting order depends on each word's length. The word lengths are fig = 3, kiwi = 4, apple = 5, and banana = 6. The words are returned from shortest to longest. The original words remain strings; the key values are used for ordering rather than replacing the items. Fig appears before kiwi because its length is smaller. Equal-length words would retain their relative input order.

Note

The key function determines how items are compared; it does not normally replace the original items with the calculated key values.

7. Handle duplicates, missing targets, and empty collections

Real input is not always as simple as a list of distinct positive integers. A robust solution should consider duplicate values, absent targets, empty collections, and the exact result the caller needs.

A linear search that returns immediately after a match finds the first occurrence. If a list contains [4, 7, 4], searching for 4 returns index zero. If you need every matching position, the algorithm must continue after finding a match.

Sorting does not remove duplicate elements. A sorted list retains the same elements and their multiplicities, only rearranged according to the ordering rule.

Sorting an empty list returns an empty list, and sorting a one-element list leaves it unchanged. Searching an empty list with a loop finds no match and should follow the function's missing-target policy.

Be careful with the type of the data being sorted. Dictionaries, for example, are not generally sortable directly against each other using their natural ordering in Python 3. To order dictionary records, provide a key function that extracts a comparable field.

Find every index of a target

Find every index of a target
python
def find_all_indices(items, target):
indices = []
 
for index, item in enumerate(items):
if item == target:
indices.append(index)
 
return indices
 
print(find_all_indices([4, 7, 4, 4, 9], 4))
print(find_all_indices([4, 7, 9], 5))
Output
[0, 2, 3] []

enumerate(items) provides each element's index and value. The function appends an index whenever its value matches the target. Unlike a first-match search, it continues through the entire list. If there are no matches, the returned list is empty.

Note

Edge-case behavior should follow the problem specification. Decide whether a missing item should produce -1, False, None, an empty list, or an exception before implementing the search.

8. Basic time complexity

Time complexity describes how the amount of work grows as the input size grows. It helps you compare approaches without depending on one particular computer's execution speed.

Linear search takes O(n) time in the worst case for a list of n elements because it may need to inspect every element. If the first element matches, it performs only one comparison, but the worst-case growth remains linear.

Comparison-based sorting with Python's built-in sorting tools has O(n log n) worst-case time complexity. For a large list, sorting generally requires more work than a single linear scan, but sorting may make later searches or repeated processing more convenient.

The membership operation on a list also has O(n) worst-case time complexity. Membership checks on dictionaries and sets are typically O(1) on average, assuming ordinary hash behavior, though their worst-case performance can be different.

Choose the algorithm based on the task. If you only need to know whether an item exists in a list, in is straightforward. If you need an index, use a search operation. If you need the data in order, sort it. Do not sort a collection unnecessarily just to perform a single existence check.

One search versus sorting

One search versus sorting
python
numbers = [8, 2, 5, 1, 9]
target = 5
 
# One membership check
print(target in numbers)
 
# Sort only when an ordered list is also required
ordered = sorted(numbers)
print(ordered)
Output
True [1, 2, 5, 8, 9]

The membership check determines whether 5 exists in the list. The sorting operation creates an ordered list for a separate requirement. For one existence check, sorting first is generally unnecessary work. If the problem also requires an ordered output, sorting may be justified. Linear search is O(n) in the worst case, while comparison-based sorting has O(n log n) worst-case time complexity.

Note

Use complexity to reason about how a solution scales, but also consider what result the task actually requires. The simplest correct operation is often the best choice.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Confusing searching with sorting.

Why it happens: Searching locates or tests for an item, while sorting rearranges items according to an ordering rule.

Incorrect Approach
script.py
python
Confusing searching with sorting.
Correct Solution
script.py
python
Searching locates or checks for a target. Sorting arranges a collection into an order.

Key takeaway: Searching locates or checks for a target. Sorting arranges a collection into an order.

#2 Assuming linear search requires a sorted list.

Why it happens: Linear search checks items one by one and works whether or not the collection is sorted.

Incorrect Approach
script.py
python
Assuming linear search requires a sorted list.
Correct Solution
script.py
python
Linear search works on unsorted collections because it checks items one by one.

Key takeaway: Linear search works on unsorted collections because it checks items one by one.

#3 Returning True or False when the task asks for an index.

Why it happens: A membership test answers whether an item exists, but an index-returning task requires finding the matching position explicitly.

Incorrect Approach
script.py
python
Returning True or False when the task asks for an index.
Correct Solution
script.py
python
Read the expected result carefully. A membership check returns a Boolean, while an index-based search returns a position or a defined missing-target result.

Key takeaway: Read the expected result carefully. A membership check returns a Boolean, while an index-based search returns a position or a defined missing-target result.

#4 Assuming sorted() changes the original list.

Why it happens: sorted() returns a new sorted list and leaves the original iterable unchanged.

Incorrect Approach
script.py
python
Assuming sorted() changes the original list.
Correct Solution
script.py
python
sorted() returns a new list. Use list.sort() when you want to modify an existing list.

Key takeaway: sorted() returns a new list. Use list.sort() when you want to modify an existing list.

#5 Assigning the result of list.sort() to a variable.

Why it happens: list.sort() sorts the list in place and returns None, so assigning its return value overwrites the variable with None.

Incorrect Approach
script.py
python
Assigning the result of list.sort() to a variable.
Correct Solution
script.py
python
list.sort() modifies the list and returns None. Call it as a statement, or use sorted() when you need a returned list.

Key takeaway: list.sort() modifies the list and returns None. Call it as a statement, or use sorted() when you need a returned list.

#6 Thinking key=len sorts by alphabetical order.

Why it happens: key=len orders strings by length, not alphabetically; use the default key or an appropriate key function for the desired order.

Incorrect Approach
script.py
python
Thinking key=len sorts by alphabetical order.
Correct Solution
script.py
python
key=len sorts by length. Use the default string ordering or another suitable key when alphabetical ordering is required.

Key takeaway: key=len sorts by length. Use the default string ordering or another suitable key when alphabetical ordering is required.

#7 Assuming sorting removes duplicate values.

Why it happens: Sorting arranges duplicates but does not remove them; use a set or an explicit deduplication strategy if uniqueness is required.

Incorrect Approach
script.py
python
Assuming sorting removes duplicate values.
Correct Solution
script.py
python
Sorting rearranges elements but retains duplicates. Use a set or another explicit deduplication approach only when removing duplicates is part of the requirement.

Key takeaway: Sorting rearranges elements but retains duplicates. Use a set or another explicit deduplication approach only when removing duplicates is part of the requirement.

#8 Calling list.index() on a value that may be missing without handling the failure.

Why it happens: list.index(value) raises ValueError if the value is absent, so check membership or handle that exception when absence is possible.

Incorrect Approach
script.py
python
Calling list.index() on a value that may be missing without handling the failure.
Correct Solution
script.py
python
Check membership first or handle the ValueError raised by index() when the value is absent.

Key takeaway: Check membership first or handle the ValueError raised by index() when the value is absent.

#9 Sorting records without specifying the field that determines their order.

Why it happens: Sorting complex records requires a key that identifies the intended field or comparison rule; relying on an unsuitable default may fail or order the wrong way.

Incorrect Approach
script.py
python
Sorting records without specifying the field that determines their order.
Correct Solution
script.py
python
Use key to extract the relevant field, such as a student's score or a product's price.

Key takeaway: Use key to extract the relevant field, such as a student's score or a product's price.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the difference between searching and sorting?
Answer:
Searching locates a target or checks whether it exists in a collection. Sorting arranges elements according to an ordering rule. Searching may return a Boolean or an index, while sorting produces an ordered collection or modifies an existing list.
Q2:How does linear search work?
Answer:
Linear search starts at the beginning of a collection and compares each element with the target. It stops when a match is found or when the collection ends. Its worst-case time complexity is O(n).
Q3:What is the difference between in and list.index()?
Answer:
The in operator returns True or False depending on whether an element exists. list.index() returns the index of the first matching element and raises ValueError if the element is absent.
Q4:What is the difference between sorted() and list.sort()?
Answer:
sorted() returns a new list and leaves the original collection unchanged. list.sort() modifies an existing list in place and returns None. Both support key and reverse parameters.
Q5:What is the purpose of the key parameter in sorting?
Answer:
The key parameter accepts a function that computes a comparison value for each item. For example, key=len sorts strings by length, while key=lambda student: student['score'] sorts student dictionaries by score.
Q6:What does reverse=True do?
Answer:
It requests the reverse of the selected sort order. With ordinary numeric sorting, it produces descending rather than ascending order.
Q7:Does linear search require sorted data?
Answer:
No. Linear search can work on an unsorted collection because it checks elements one at a time. A sorted list is required by algorithms such as binary search, but not by linear search.
Q8:What is the time complexity of linear search and Python's built-in sorting?
Answer:
Linear search takes O(n) time in the worst case for n elements. Python's built-in comparison-based sorting has O(n log n) worst-case time complexity.
Q9:How would you find every occurrence of a target in a list?
Answer:
Iterate through the list using enumerate(), compare each element with the target, and append the index of every match to a result list. Do not return immediately after the first match.
Q10:Why is Python's stable sorting useful?
Answer:
Stability preserves the relative order of elements whose sort keys are equal. This is useful when sorting records by multiple fields in successive passes or when equal-key items should retain their previous order.

Key takeaways

  • Searching finds a target or checks whether it exists; sorting arranges data into a specified order.
  • Linear search examines elements sequentially and works on unsorted lists.
  • The in operator checks membership and returns a Boolean.
  • list.index() returns the first matching index and raises ValueError if the target is absent.
  • sorted() returns a new list, while list.sort() modifies the existing list and returns None.
  • reverse=True requests descending order for ordinary numeric sorting.
  • The key parameter lets you sort strings by length or records by a selected field.
  • Sorting preserves duplicate elements, and Python's built-in sorting is stable.
  • Linear search has O(n) worst-case time complexity; Python's built-in sorting has O(n log n) worst-case time complexity.
  • Choose an operation based on the required result, the collection type, and the problem's constraints.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: