In the last basic python statement tutorial, we explained some important characteristics or rules of python statements. After knowing this, here we will show some rules and techniques regarding assignment statements.

Anywhere you use the equal operator(=) you are performing assignment and the statement is called assignment statement. In python programming language, when we assign a name to an object python creates a reference number or id to the object in the run time. This id can be checked using the id method. Some examples of name assignment and the corresponding temporal id are shown below.



x = 3id(x)
2009872176y = 'string'id(y)
5365344


In other words internally, Python uses pointers to creates reference to objects so that each object has unique id. If we assign two names such as a and b to the some object like integer in single line then the two object will have two names but same reference number.

a = b = 8id(a)
2009872256id(b)
2009872256

You can see that the names a and b have the same id.

Another rule using assignment statement is that the names must be declared beforehand the name is referenced in the program. Otherwise python will throw error.

Different ways of doing assignment in Python

The basic assignment statement is like the following.

x = 3

But you can also do multiple assignment in the same line as shown below.

a = b = 8

 or,

a = 4; b = 9>>> a
4>>> b
9

 or,


a, b = 5, 6>>> a
5>>> b
6

 or, you can perform assignment using list type or sequential type:

[a, b] = [7, 8]
>>> a
7>>> b
8


If we use multiple assignment technique like the ones above, the number of names and objects on left and right side must match.

s = 'abc'x, y, z = s
>>> x
'a'>>> y
'b'>>> z
'c'

Assigning core data  objects to each other

Assigning tuple to List: here tuple (1,2) is assigned to list [a,b]

[a, b] = (1, 2)
>>> a
1>>> b
2

 Assigning string to tuple: here string is assigned to tuple

(a,b,c,d) = "name">>> a
'n'>>> b
'a'>>> c
'm'>>> d
'e'


Indexing and Slicing type Assignment

Consider a string s. We can use the indexing and slicing technique to assign various substring or characters to new named objects.

s = "my string"s1, s2 = s[0:2], s[3:9]
>>> s
'my string'>>> s1
'my'>>> s2
'string'


0 comments:

Post a Comment

 
Top