Python Sort a List Alphabetically
To sort a list alphabetically in Python, you can use the following two methods:
- sort() method -- that is, it modifies the original list directly and does not create a new sorted copy; this method changes the order of the original list and does not return a new sorted list.
- sorted() function -- creates a new sorted list without modifying the original list; this function returns a new sorted list and the original list stays unchanged.
sort() method example:
Example
my_list
=
[
"apple"
,
"banana"
,
"cherry"
,
"date"
]
my_list.
sort
(
)
Sort alphabetically
(
my_list
)
Running the code above produces:
['apple', 'banana', 'cherry', 'date']
sorted() function example:
Example
my_list
=
[
"apple"
,
"banana"
,
"cherry"
,
"date"
]
sorted_list
=
sorted
(
my_list
)
Create a new sorted list
(
sorted_list
)
Running the code above produces:
['apple', 'banana', 'cherry', 'date']
Either method can sort a list alphabetically. If you want the reverse alphabetical order (descending), you can pass the reverse=True parameter to the sort() method or the sorted() function.
sort() method:
Example
my_list
=
[
"apple"
,
"banana"
,
"cherry"
,
"date"
]
my_list.
sort
(
reverse
=
True
)
Sort in descending alphabetical order
(
my_list
)
sorted() function:
Example
my_list
=
[
"apple"
,
"banana"
,
"cherry"
,
"date"
]
sorted_list
=
sorted
(
my_list
,
reverse
=
True
)
Create a new sorted list in descending alphabetical order
(
sorted_list
)
Python3 Examples