Lists
Lists
>>> x = ['120','130','210','230’]
>>> x[0]
'120’
>>> x[-1]
'230’
>>> x[len(x)-1]
‘230’
>>> z=[1,3[,’ok’,[9,8,7]]
>>> z[3]
[9,8,7]
>>>z[3][1]
8
Indexes, accessing multiple elements
>>> x=['one','two','three','four']
>>> x[0:3]
['one', 'two', 'three']
>>> x[1:-1] #1st argument needs to be smaller than 2nd argument
['two', 'three']
Indexes, accessing multiple elements
>>> x=['one','two','three','four']
>>> x[:3] #from begin to target-1
['one', 'two', 'three']
>>> x[2:] #from target to end
['three’, ‘four’]
Reference to same list
>>> x=['one','two','three','four']
>>> y = x #y & x reference same list
>>> y[0]='ok’
>>> y
['ok', 'two', 'three', 'four']
>>> x
['ok', 'two', 'three', 'four']
Separate copy of list
>>> x=['one','two','three','four']
>>> w = x[:] #w gets a separate copy of x
>>> x
['one', 'two', 'three', 'four']
>>> w[0]='ok’
>>> w
['ok', 'two', 'three', 'four']
>>> x
['one', 'two', 'three', 'four’]
OR
>>> w2 = x.copy() # w2 has has a separate copy of x
Adding Single item to list
>>> x = [9,7,8,4,1,5]
>>> x.sort()
>>> x
[1,4,5,7,8,9]
>>> x = [9,’abc’,1,5]
>>> x.sort()
Error, cant sort with mixed types
>>> x = [9,1,5]
>>> x.sort(reverse=True)
>>> x
[ 9 , 5, 1 ]
List membership
>>> x = [9,’abc’,1,5]
>>> 9 in x
True
>>> 7 in x
False
>>> 7 not in x #use of not
True
List concatenation