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
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
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
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
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
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
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
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
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()
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
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
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
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
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
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
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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?
Q2:How does linear search work?
Q3:What is the difference between in and list.index()?
Q4:What is the difference between sorted() and list.sort()?
Q5:What is the purpose of the key parameter in sorting?
Q6:What does reverse=True do?
Q7:Does linear search require sorted data?
Q8:What is the time complexity of linear search and Python's built-in sorting?
Q9:How would you find every occurrence of a target in a list?
Q10:Why is Python's stable sorting useful?
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.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: