I am a bit confused regarding data structure in python; ()
,[]
, and {}
. I am trying to sort 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?
This question is related to
python
list
sorting
alphabetical
>>> a = ()
>>> type(a)
<type 'tuple'>
>>> a = []
>>> type(a)
<type 'list'>
>>> a = {}
>>> type(a)
<type 'dict'>
>>> a = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
>>> a.sort()
>>> a
['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']
>>>
ListName.sort()
will sort it alphabetically. You can add reverse=False/True
in the brackets to reverse the order of items: ListName.sort(reverse=False)
You can use built-in sorted
function.
print sorted(['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue'])
You're dealing with a python list, and sorting it is as easy as doing this.
my_list = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
my_list.sort()
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)
)).
>>> x = [3,2,1]
>>> sorted(x)
[1, 2, 3]
>>> x
[3, 2, 1]
Lists also have a sort
method that will perform the sort in-place (x.sort() returns None but changes the x object) .
>>> x = [3,2,1]
>>> x.sort()
>>> x
[1, 2, 3]
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:
>>> x = {3:2,2:1,1:5}
>>> sorted(x.items(), key=lambda kv: kv[1]) # Items returns a list of `(key,value)`-pairs
[(2, 1), (3, 2), (1, 5)]
Source: Stackoverflow.com