I am a bit confused regarding data structure in python; ()
,[]
, and {}
. I am trying to sort out a simple list, probably since I cannot identify the type of data I am failing to sort it.
My list is simple: ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
My question is what type of data this is, and how to sort the words alphabetically?
Python has a built-in function called
sorted
, which will give you a sorted list from any iterable you feed it (such as a list ([1,2,3]
); a dict ({1:2,3:4}
, although it will just return a sorted list of the keys; a set ({1,2,3,4
); or a tuple ((1,2,3,4)
)).Lists also have a
sort
method that will perform the sort in-place.Both also take a
key
argument, which should be a callable (function/lambda) you can use to change what to sort by.For example, to get a list of
(key,value)
-pairs from a dict which is sorted by value you can use the following code:You can use built-in
sorted
function.[]
denotes a list,()
denotes a tuple and{}
denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.What you have is a list of strings. You can sort it like this:
As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:
You can also sort the list in reverse order by doing this:
Please note: If you work with Python 3, then
str
is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data typeunicode
in Python 2, and notstr
. In such a case, if you have a list of unicode strings, you must writekey=unicode.lower
instead ofkey=str.lower
.You're dealing with a python list, and sorting it is as easy as doing this.
ListName.sort()
will sort it alphabetically. You can addreverse=False/True
in the brackets to reverse the order of items:ListName.sort(reverse=False)