To retrieve the unique values from a given list, you can leverage several methods in Python. Let's explore the different techniques and their relative efficiency.
This involves iterating through the list, checking if each element is already in a result list output. If it is not present, it is added to output. While straightforward, this approach has a time complexity of O(n^2) due to the membership checking operation within the loop.
A more efficient solution is to convert the list to a set. Sets are unordered collections of unique elements, sehingga menghilangkan duplikat secara otomatis. Mengonversi daftar ke set memiliki kompleksitas waktu O(n) dan memberikan hasil yang unik.
Untuk mengubah daftar menjadi set, gunakan kode berikut:
myset = set(mylist)
Untuk mengubah kembali set menjadi list jika diperlukan, gunakan:
mynewlist = list(myset)
Instead of converting a list to a set and then back to a list, you can create a set directly from the start. This approach also has a time complexity of O(n) and eliminates the need for conversion operations.
The code would look like this:
output = set() for x in trends: output.add(x)
It's worth noting that sets do not maintain the original order of elements. If preserving the order is crucial, consider using an ordered set implementation (refer to this question for details).
The above is the detailed content of How Can I Efficiently Extract Unique Values from a Python List?. For more information, please follow other related articles on the PHP Chinese website!