

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate a sorted list in Python?
The sort method on lists in python uses the given class's gt and lt operators to compare. Most built in classes already has these operators implemented so it automatically gives you sorted list. You can use it as follows:
words = ["Hello", "World", "Foo", "Bar", "Nope"] numbers = [100, 12, 52, 354, 25] words.sort() numbers.sort() print(words) print(numbers)
This will give the output:
['Bar', 'Foo', 'Hello', 'Nope', 'World'] [12, 25, 52, 100, 354]
If you don't want the input list to be sorted in place, you can use the sorted function to do so. For example,
words = ["Hello", "World", "Foo", "Bar", "Nope"] sorted_words = sorted(words) print(words) print(sorted_words)
This will give the output:
["Hello", "World", "Foo", "Bar", "Nope"] ['Bar', 'Foo', 'Hello', 'Nope', 'World']
- Related Questions & Answers
- How to generate all permutations of a list in Python?
- Program to merge two sorted list to form larger sorted list in Python
- Python program to create a sorted merged list of two unsorted list
- How a list can be sorted in Java
- Find missing numbers in a sorted list range in Python
- Python Generate successive element difference list
- Generate a list of Primes less than n in Python
- Python - Inserting item in sorted list maintaining order
- How to remove duplicates from a sorted linked list in android?
- Python program to insert an element into sorted list
- Convert list of string into sorted list of integer in Python
- Python program to create a sorted merged list of two unsorted lists
- Square list of elements in sorted form in Python
- How to generate sequences in Python?
- Program to find squared elements list in sorted order in Python
Advertisements