Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Sort a List Alphabetically

Python Sort a List Alphabetically

Document Object Reference Manual Python3 Examples

To sort a list alphabetically in Python, you can use the following two methods:

sort() method example:

Example

my_list

=

[

"apple"

,

"banana"

,

"cherry"

,

"date"

]

my_list.

sort

(

)

 

Sort alphabetically

print

(

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

print

(

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

print

(

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

print

(

sorted_list

)

Document Object Reference Manual Python3 Examples