Lists are python's powerful array data type - but they are much more than the regular arrays you may be used to. You can have as many elements in an array as you wish!
In [3]:
x = [1,2,3]
type(x)
Out[3]:
You can freely mix datatypes in a list!
In [5]:
x = [0, "hello", 0.5, 1e6]
print x
Addressing array elements can be done using an index
In [7]:
print x[0]
print x[1]
print x[-1] # Last element!
To get the number of elements in a list, use len()
In [8]:
len(x)
Out[8]:
"Slices" of arrays can be created. This makes playing around with lists easy and effortless !
In [1]:
x = [0, "hello", 0.5, 1e6]
print x[0:2] # first two elements -- elements index 0 to 2, not including 2
print x[-2:] # last two elements!
print x[1:-1] # between second and second last!
print x[::2] # even numbered elements!
print x[1::2] # odd numbered elements
print x[:] # all elements
You may use the exchange trick too...
In [15]:
x[0:2],x[2:4] = x[2:4],x[0:2]
print x
Extracting values from a list to other variables is easy too!
In [18]:
a,b = x[0:2]
print a, b
List operations:
In [9]:
x = [1,2,3]
pos = 0
x.insert(pos,5) # insert at given position
x.append(4) # adds at the end of the list
print x.pop() # removes last element, returns it
print x
There are no 2D arrays in python. You achieve the same by nesting lists - i.e. making list elements that are themselves lists.
In [20]:
mat = [
[0,1,2],
[3,4,5],
[7,8,9]
]
print mat
Note that this simulated 2D array is not really a 2D array in the regular sense. E.g. the following are ok
In [24]:
mat2 = [
[0,1,2],
[],
[1]
]
print mat2
print mat2[0][0]
But the usage below results in an error... For the simple reason that there are no elements in the second "row"!
In [25]:
print mat2[1][0]
A primitive operation on arrays is sorting. Achieving a sort is easy...
In [28]:
x = [1, 20, 5, 30]
print x
x.sort()
print "Sorted array"
print x
The "sorted" builtin returns a sorted copy of the array...
In [29]:
x = [1, 20, 5, 30]
y = sorted(x)
print x
print y
Python makes it easy to check list membership - i.e. whether something belongs to a list or not. The "in" operator tests membership.
In [31]:
x = [1, 50, 80, 90]
print 0 in x
print 50 in x
"not"ting the output inverts the membership check :
In [32]:
print 0 not in x
Note the resulting improvement in readability of the code. The same can be achieved by not (0 in x).
In [33]:
print not(0 in x)
You may use del to delete an element in the array
In [2]:
x = [1,2,3]
del x[1] # remove second element
print x
del works on slices also.
In [4]:
x = [1,2,3]
del x[1:]
print x
del x[:]
print x
List may be reversed
In [5]:
x = [1,2,3]
x.reverse()
print x
Note that deleting all the elements in the list only makes the list empty. It does not delete the list!
Exercise:
Write python code to rotate a list. Assume that list has at-least one element.