Python – Variables

Python Variables

A variable is a memory place where data is stored (value). To distinguish between distinct memory locations, they are given unique names. In Python, the rules for writing variable names are the same as the rules for writing identifiers. Before utilizing a variable, we don’t need to declare it. We can just assign a value to a variable in Python, and it will exist. We don’t even need to declare the variable’s type. The sort of value we assign to the variable determines how this is handled internally.

Variable assignment

We use the assignment operator (=) to assign values to a variable. Any type of value can be assigned to any valid variable.

a = 5
b = 3.2
c = "Hello"

There are three assignment statements in this section. The integer 5 has been assigned to the variable a. Similarly, the variables b and c are assigned to 3.2 as a floating point value and “Hello” as a string (sequence of characters).

Multiple assignments

In Python, multiple assignments can be made in a single statement as follows:

a, b, c = 5, 3.2, "Hello"

If we want to assign the same value to multiple variables at once, we can do this as

x = y = z = "same"

This assigns the “same” string to all the three variables.

Data types in Python

In Python, each value has a datatype. Data types are essentially classes, and variables are instances (objects) of these classes, because everything in Python programming is an object. Python has a number of different data types. The following are some of the more important types.

Python Numbers

Integers, floating point numbers, and complex numbers are all examples of Python numbers. They are known as the int, float, and complex classes in Python. The type() method can be used to find out which class a variable or value belongs to, and the isinstance() function can be used to see if an object belongs to a particular class.

a = 5
print(a, "is of type", type(a))

a = 2.0
print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))


5 is of type 
2.0 is of type 
(1+2j) is complex number? True

Integers can have any length; the only limitation is the amount of memory available. Up to 15 decimal digits, a floating point number is accurate. Decimal points separate integers and floating points. The numbers 1 and 1.0 are integers and floating point numbers, respectively. The formula for complex numbers is x + yj, where x is the real part and y is the imaginary part. Here are a few illustrations.

>>> a = 1234567890123456789
>>> a
>>> b = 0.1234567890123456789
>>> b
>>> c = 1+2j
>>> c

Notice that the float variable b got truncated.

Python List

A list is a collection of items in a specific order. It is an extremely flexible datatype that is one of the most commonly used in Python. It is not necessary for all items in a list to be of the same type. Declaring a list is rather simple. Commas divide items, which are enclosed in brackets [].

>>> a = [1, 2.2, 'python']

We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python.

a = [5,10,15,20,25,30,35,40]

# a[2] = 15
print("a[2] = ", a[2])

# a[0:3] = [5, 10, 15]
print("a[0:3] = ", a[0:3])

# a[5:] = [30, 35, 40]
print("a[5:] = ", a[5:])


a[2] =  15
a[0:3] =  [5, 10, 15]
a[5:] =  [30, 35, 40]

Lists are mutable, meaning, value of elements of a list can be altered.

Python Tuple

The same as a list, a tuple is an ordered series of items. Tuples vary solely in that they are immutable. Tuples can’t be changed once they’ve been generated. Tuples are used to write-protect data and, because they do not alter dynamically, are usually faster than lists. It is defined within parenthesis (), with commas between the pieces.

>>> t = (5,'program', 1+3j)

We can use the slicing operator [] to extract items but we cannot change its value.

t = (5,'program', 1+3j)

# t[1] = 'program'
print("t[1] = ", t[1])

# t[0:3] = (5, 'program', (1+3j))
print("t[0:3] = ", t[0:3])

# Generates error
# Tuples are immutable
t[0] = 10


t[1] =  program
t[0:3] =  (5, 'program', (1+3j))

Traceback (most recent call last):
  File "", line 11, in 
    t[0] = 10
TypeError: 'tuple' object does not support item assignment

Python Strings

The term “string” refers to a collection of Unicode characters. To represent strings, we can use single or double quotations. Triple quotes, “‘ or “””, can be used to signify multi-line strings.

>>> s = "This is a string"
>>> s = '''a multiline

Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.

s = 'Hello world!'

# s[4] = 'o'
print("s[4] = ", s[4])

# s[6:11] = 'world'
print("s[6:11] = ", s[6:11])

# Generates error
# Strings are immutable in Python
s[5] ='d'


s[4] =  o
s[6:11] =  world

Traceback (most recent call last):
  File "", line 11, in 
    s[5] ='d'
TypeError: 'str' object does not support item assignment

Python Set

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.

a = {5,2,3,1,4}

# printing set variable
print("a = ", a)

# data type of variable a


a =  {1, 2, 3, 4, 5}

We can perform set operations like union, intersection on two sets. Set have unique values. They eliminate duplicates.

>>> a = {1,2,2,3,3,3}
>>> a
{1, 2, 3}

Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not work.

>>> a = {1,2,3}
>>> a[1]
Traceback (most recent call last):
  File "", line 301, in runcode
  File "", line 1, in 
TypeError: 'set' object does not support indexing

Python Dictionary

A dictionary is a collection of key-value pairs that are not in any particular sequence. When we have a large amount of data, we usually use it. The retrieval of data is enhanced in dictionaries. To get the value, we need to know the key. In Python, dictionaries are defined between brackets, with each item being a key:value pair. Any type of key and value can be used.

>>> d = {1:'value','key':2}
>>> type(d)

We use key to retrieve the respective value. But not the other way around.

d = {1:'value','key':2}

print("d[1] = ", d[1]);

print("d['key'] = ", d['key']);

# Generates error
print("d[2] = ", d[2]);


d[1] =  value
d['key'] =  2

Traceback (most recent call last):
  File "", line 9, in 
    print("d[2] = ", d[2]);
KeyError: 2

Conversion between data types

We can convert between different data types by using different type conversion functions like int(), float(), str() etc.

>>> float(5)

Conversion from float to int will truncate the value (make it closer to zero).

>>> int(10.6)
>>> int(-10.6)

Conversion to and from string must contain compatible values.

>>> float('2.5')
>>> str(25)
>>> int('1p')
Traceback (most recent call last):
  File "", line 301, in runcode
  File "", line 1, in 
ValueError: invalid literal for int() with base 10: '1p'

We can even convert one sequence to another.

>>> set([1,2,3])
{1, 2, 3}
>>> tuple({5,6,7})
(5, 6, 7)
>>> list('hello')
['h', 'e', 'l', 'l', 'o']

To convert to dictionary, each element must be a pair

>>> dict([[1,2],[3,4]])
{1: 2, 3: 4}
>>> dict([(3,26),(4,44)])
{3: 26, 4: 44}

Leave a Comment

Your email address will not be published.