This is continuation from Python Notes-1. We were learning about python list
li = 
I really like the way python never need the variable to be declared. It is automatically assigned the data type based on it’s last initialization. e.g.
a = 9 a = 'q'
>>> a = 9
>>> a = 'q'
>>> a = 
As we know from last post that python string are immutable similarly we have another data structure in python called tuple which is similar to list but it is immutable.
var = ()
var = ('abc',3,4.8)
You can’t do
var = 3 also if there is only one element in the tuple it doesn’t make sense to write it like
var = (2) or
var = (x) as this will just mean
var = 2 or
var = x. So you have to do it like
var = (2,) or
var = (x,). One item tuple will need a trailing comma.
len() will give you length of a variable like
var = "12345" then
len(var) will be 5.
var = [1,2,3,4,5] len(var)
Negative index This is very handy in accessing elements from last so you can say:
This will give you the last element of the list. This can be applied similarly to list or tuple
var = [1,2,3,4,5]
-2 will refer to second last element.
var = ['apple', 'ball', 'cat', 'dog']
['ball', 'cat', 'dog']
Reading from standard input
var = input()
var will be of str type. Also note that Python doesn’t have char data type.
var = int(input())
will try to convert what is read to int.
One important list method is append()
used extensibly in a loop to keep on adding things.
insert() method to insert at a particular index first argument is index second argument is what to insert. insert(indx,val)
li = [1, 2]
[1, 2, 3, 4]
[1, 2, 3, 3, 4]
[1, 2, 3, 4]
A sample code
To be continued …