Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- a = [2,10,4,3,7]
- a.sort()
- print(a)
- # returns a new sorted list without modifying source list
- a = [2,10,4,3,7]
- print(sorted(a))
- print(a)
- # sort method with different type of objects
- a = ["hello", 1, "world", 45, 2]
- # a.sort() comparing int 2 str s not allowed in Python 3.x
- print(a)
- # function as a sort key
- a = [[2,3], [4,6], [6,1]]
- a.sort(key=lambda x: x[1])
- print(a)
- a = ['python', 'perl', 'java', 'c', 'haskell', 'ruby']
- # sorts a list of strings based on length
- def lensort(a):
- a.sort(key=len)
- print(a)
- lensort(a)
- a = ['python', 'java', 'Python', 'Java']
- # sorts a list of unique string
- def unique(a):
- u = list(set(word.lower() for word in a))
- u.sort()
- print(u)
- unique(a)
- # tuples
- a = (1,2,3)
- print(a[0])
- a = 1,2,3
- print(a[1])
- print(len(a))
- print(a[0:])
- print(a[1:])
- # sets
- x = set([3,1,2,1])
- print(x)
- # other way of writing sets
- x = {3,2,1,3} # no need to use set word
- print(x)
- # add elements to a set using add method
- x = set([1,2,3])
- x.add(4)
- print(x)
- # existence of an element using in operator
- x = set([1,2,3])
- print(1 in x)
- print(5 in x)
- # strings
- print(len("abrakadabra"))
- a = "hello world"
- print(a[-4])
- print(a[::-1])
- print(a.split()) # creating a list
- b = "a,b,c"
- print(b.split(',')) # like above
- c = "hello"
- d = "world"
- print(" ".join([c,d])) # join strings
- print(b.strip(' world')) # strip letter
- # formating values into strings
- print("%s %s" % (c,d))
- print('Cahpter %d: %s' % (3, 'Data Structures'))
- # sorting by extension
- a = ['a.c', 'a.py', 'b.py', 'bar.txt', 'foo.txt', 'x.c']
- import os.path
- def extsort(a):
- a.sort(key=lambda f: os.path.splitext(f))
- print(a)
- extsort(a)
Advertisement
Add Comment
Please, Sign In to add comment