Python Notes-2

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
>>> type(a)

>>> a = 'q'
>>> type(a)

>>> a = []
>>> type(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[0] = 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.
Similarly var = [1,2,3,4,5] len(var)

Negative index This is very handy in accessing elements from last so you can say:

var = [1,2,3,4,5]
This will give you the last element of the list. This can be applied similarly to list or tuple
-2 will refer to second last element.


var = ['apple', 'ball', 'cat', 'dog']
>>> spam[:2]
['apple', 'ball']
>>> spam[1:]
['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]
>>> li.append(4)
>>> li.insert(2,3)
>>> li
[1, 2, 3, 4]
>>> li.insert(2,3)
>>> li
[1, 2, 3, 3, 4]
>>> del(li[2])
>>> li
[1, 2, 3, 4]

A sample code

To be continued …


10 thoughts on “Python Notes-2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s