Friday 3 January 2014

Python List and Tuple


List and Tuple are the two very useful build-in sequences in Python.

  • List: an ordered sequence which can be changed. Insert, delete, update. [element1, element2]
  • Tuple: an ordered sequence which are immutable. It is faster than List. (element1, element2)


Common Methods:

1.       index: the sequence have indexes, starting from 0.  minus index indicates started from the right.
>>> #define a list
>>> mylist=['one','two','three']
>>> mylist[0]
'one'
>>> mylist[2]
'three'
>>> mylist[-1]
'three'

>>> 

2.       slice : get the range from the existing sequence, minus index (means from the right) or no index (means from start or end)
>>> mynumbertuple=(1,2,3,4,5,6,7,8,9,10,)
>>> mynumbertuple[3:5]
(4, 5)
>>> mynumbertuple[3:-3]
(4, 5, 6, 7)
>>> print mynumbertuple[-3:]
(8, 9, 10)
>>> print mynumbertuple[3:]

(4, 5, 6, 7, 8, 9, 10)

3.       plus (+) : join the same type of sequence together.
>>> mylist = [1,2,3,] + [4,’5’,6]
>>> print mylist

[1, 2, 3, 4, ‘5’, 6]

4.       multiply (*) : repeat the sequence with multiple times.
>>> mynewtuple = (1,2,3)*3
>>> print mynewtuple

(1, 2, 3, 1, 2, 3, 1, 2, 3)

5.       in - check if the memer is in the sequence.
>>> mynumbertuple
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> 2 in mynumbertuple
True
>>> 10 in mynumbertuple
True
>>> 20 in mynumbertuple

False

6.       len, min, max build-in functions.
  • len: get the length of the sequence
  • min, get the min value of the sequence
  • max, get the max value of the sequence

>>> len(mynumbertuple)
10
>>> max(mynumbertuple)
10
>>> min(mynumbertuple)

1

Because the list is mutable, there are a few useful functions for list.

1.       set the value
list[index] =  newvalue
2.       delete value
del list[index]
or tricky way list[index] = []

>>> mylist = [1,2,3,4,5]
>>> mylist[3]=40                 #set the 3rd element to 40
>>> mylist
[1, 2, 3, 40, 5]
>>> del mylist[-1]                #delete the last element
>>> mylist
[1, 2, 3, 40]
>>> mylist[1:2] = []             #delete the 2nd element.
>>> mylist

[1, 3, 40]

3.       append(): add one object to the list
4.       extend(): combine the new list to the previous list
>>> list1=[1,2,3]
>>> list2=[1,2,3]
>>> list1.append([4,5,6])
>>> list1
[1, 2, 3, [4, 5, 6]]
>>> list2.extend([4,5,6])
>>> list2

[1, 2, 3, 4, 5, 6]

5.       count(). Count the counters in the sequence for an element.
>>> [1,2,3,4,1,2,3,5].count(3)

2

6.       index(). Get the first index of the element
>>> [1,2,3,5,1,2,3,5].index(5)


7.       remove(): remove the first matched element from the list
>>> mylist = [1,3,5,7,2,4,6,8,5]>>> mylist.remove(5)>>> mylist[1, 3, 7, 2, 4, 6, 8, 5]

8.       sort(): sort the elements
>>> mylist.sort()
>>> mylist
[1, 2, 3, 4, 5, 6, 7, 8]

9.       reverse(): reverse the elements
>>> mylist.reverse()
>>> mylist

[8, 7, 6, 5, 4, 3, 2, 1]

No comments:

Post a Comment