Python Tutorial

Thursday, June 7, 2012

python string array sort: pass custom function



Sorted is very easy to use. We can use both built-in and custom function for sorting. Some example are given here. Remember it always return a new array by kipping the original array



a=["Life", "is", "very","easy", "with", "python"]

def myFunction(data):
    return data[0]

print sorted(a)
print sorted(a,key=myFunction)
print sorted(a,key=len)
print sorted(a)



Output:
['Life', 'easy', 'is', 'python', 'very', 'with']
['Life', 'easy', 'is', 'python', 'very', 'with']
['is', 'Life', 'very', 'easy', 'with', 'python']
['Life', 'easy', 'is', 'python', 'very', 'with']

0 comments:

Post a Comment