Updated date:

Variables in Python

I'm a software developer with a great interest in data analysis and statistics.

variables-in-python

Just like any programming language, variables in Python are reserved memory locations to store values in them. Unlike other programming languages like C, C++, Java, etc, Python does not require one to explicitly declare the type of the variable before assigning a value to it. In fact, memory is reserved for the variable as soon as a value is assigned to it and the interpreter takes care of it at runtime.

Assigning Values to Python Variables

Consider the following code:

#!/usr/bin/python3
a = 10;
b = 20;
name = "Sammy"
print(a)
print(b)
print('Hello ', name)
print(a+b)

The output of the above code will be:

10
20
Hello Sammy
30     

Let us analyze the above code to learn more.

Notice the first line starting with #!. This is called a shebang or hash-bang or pound-bang line. This is particularly useful in case of Unix environment where you can convert the .py file into an executable and run it as:

./test.py

The hash-bang line in the starting of the file serves as an interpreter directive and gives the file as an input to the python interpreter located at /usr/bin/python3.

Since a and b are implicitly reserved spaces and treated as numbers by the interpreter, the last line prints the sum of a and b.

Dealing With Multiple Assignments

If more than one variables need to be initialized with the same value, Python allows you to do the declaration and assignment in a single line. Eg:

#!/usr/bin/python3
x=y=z=0
print(x)
print(y)
print(z)

The output for the above code will be:

It is perfectly legal to initialize heterogeneous values in the following way:

#!/usr/bin/python3
name, age, dob = 'Sammy', 25, "01-01-1990"
print("Name: ", name)
print("Age: ", age)
print("DOB: ", dob)

The output of the above code will be:

Name:  Tom
Age: 25
DOB:  01-01-1990

Notice that unlike other languages, it is perfectly fine to use single quotes or double quotes for representing a String value. However, care should be taken not to mix these two and use different quotes at the start and end of the String literal.

Data Types

In the previous section, we saw a glimpse of two data types in Python – numbers, and strings. In this section, we will learn more about the data types in python.

Python has 5 standard data types.

Numbers

As the name suggests, the number data type is used to store numerical values. Numbers are represented as objects and memory is allocated to them as soon as we assign them a value. It is possible to use del statement to delete the reference to a number object.

There are four types of numbers supported by Python. They are:

  • Int – represents signed integers
  • Long – long values represented with a trailing L to distinguish between int and long types.
  • Float – floating point values.
  • Complex – complex numbers that are represented as a+bi where a and b are real values and I represent the imaginary unit of the complex number.

Strings

They represent a continuous set of characters enclosed in single or double quotation marks. To get a character at a given position I, we use str[i]. We can get substrings using the slice operator[:]. Just like Java, string concatenation can be done using a + sign. It is possible to repeat the string n times by using * operator.

Let us learn more about this with an example:

#!/usr/bin/python3
myString = "Welcome To String Tutorial!"
print (myString)          # Prints complete string
print (myString[0])       # Prints first character of the string
print (myString[8:10])    # Prints characters starting from 3rd to 5th. So, should print "To" alone.
print (myString[8:])      # Prints string starting from the second word "To". The second word's starting letter is at myString[8]
print (myString * 4)      # Prints the string four times.
print (myString + "TEST") # Prints concatenated string with Test

Output of the above program will be:

Welcome To String Tutorial!
W
To
To String Tutorial!
Welcome To String Tutorial!Welcome To String Tutorial!Welcome To String Tutorial!Welcome To String Tutorial!
Welcome To String Tutorial!TEST

Lists

Python Lists have some similarities and some differences with traditional arrays in C, C++, Java, etc. The similarity between the Python list and an array in a language like Java is that the list is represented using comma separated values enclosed inside square brackets. But unlike arrays which always contain homogeneous data types, lists can contain heterogeneous types.

Almost all the operations we saw in the example written for Strings subsection are applicable in case of lists. The ith element in case of a list can be accessed using list[i]. Using a slice operator, we can get elements in a range of indices of the list. Using + sign, we can concatenate two lists. Using *, we can repeat a list.

#!/usr/bin/python3

myList = [ 'Welcome', "To" , "List", 'Tutorial', 3.0 ]
studentData = ['john', "smith", 29, 415312]

print(myList)               # Prints complete list
print(myList[0])            # Prints first element of myList
print(studentData[1:3])     # Prints smith and 29 as they are 2nd and 3rd element of the list.
print(myList[2:])           # Prints elements starting from 3rd element
print(studentData * 2)      # Prints list studentDatatwo times
print(myList + studentData) # Prints concatenated lists

The output of the above program will be:

['Welcome', 'To', 'List', 'Tutorial', 3.0]
Welcome
['smith', 29]
['List', 'Tutorial', 3.0]
['john', 'smith', 29, 415312, 'john', 'smith', 29, 415312]
['Welcome', 'To', 'List', 'Tutorial', 3.0, 'john', 'smith', 29, 415312]

Tuples

Tuples are similar to lists where individual elements are separated using commas. All the operations that were discussed in the previous example for Lists subsection are applicable for tuples as well.

Unlike lists, tuples are grouped using parentheses() instead of square brackets[]. Moreover, elements in a tuple are not modifiable but a list can be modified once it is created.

#!/usr/bin/python3

firstTuple = ( 'Welcome', "To" , "List", 'Tutorial', 3.0  )
firstList = [ 'Welcome', "To" , "List", 'Tutorial', 3.0  ]
secondTuple = ('john', "smith", 29, 415312)

print(firstTuple)               # Prints complete tuple
print(firstTuple[0])            # Prints first element of the firstTuple
print(firstTuple[1:3])          # Prints elements starting from 2nd till 3rd of firstTuple
print(firstTuple[2:])           # Prints elements starting from 3rd element of firstTuple
print(secondTuple * 3)            # Prints the secondTuple three times
print(firstTuple + secondTuple)   # Prints concatenated tuples

firstList[2] = 1000     # Valid syntax with list
print("firstList values after modification:")
print(firstList)
firstTuple[2] = 1000    # Invalid syntax with tuple
print("firstTuple values after modification:")
print(firstTuple)

The output of the above program will be:

('Welcome', 'To', 'List', 'Tutorial', 3.0)
Welcome
('To', 'List')
('List', 'Tutorial', 3.0)
('john', 'smith', 29, 415312, 'john', 'smith', 29, 415312, 'john', 'smith', 29, 415312)
('Welcome', 'To', 'List', 'Tutorial', 3.0, 'john', 'smith', 29, 415312)
firstList values after modification:
['Welcome', 'To', 1000, 'Tutorial', 3.0]
Traceback (most recent call last):
  File "G:\workspaces\py_ws\MyProj\org\pythontutorials\examples\TupleVsList.py", line 22, in <module>
    firstTuple[2] = 1000    # Invalid syntax with tuple
TypeError: 'tuple' object does not support item assignment

Notice the error thrown at end of the output while we try to modify a tuple’s element. This is because tuples are treated as read-only lists.

Dictionary

Dictionaries in Python consist of comma-separated key-value pairs enclosed within curly braces{}. Keys in a dictionary are usually numbers or strings. Values can be of any type and can be assigned or accessed using square brackets.

#!/usr/bin/python3

firstDict = {}
firstDict['Welcome'] = "Welcome To The Tutorial"
firstDict[2]     = "This is second value"

studentDict = {'firstName': 'john','lastName':'Smith', 'age': 29, 'studentId':415312}


print(firstDict['Welcome']) # Prints value for 'Welcome' key
print(firstDict[2])         # Prints value for 2 key
print(studentDict)          # Prints complete studentDict
print(studentDict.keys())   # Prints all the keys of studentDict
print(studentDict.values()) # Prints all the values of studentDict

The output of the above program will be:

Welcome To The Tutorial
This is second value
{'studentId': 415312, 'age': 29, 'lastName': 'Smith', 'firstName': 'john'}
dict_keys(['studentId', 'age', 'lastName', 'firstName'])
dict_values([415312, 29, 'Smith', 'john'])

To Sum Up

In this tutorial, we saw how Python handles variables and allocates memory for them. We also learned how Python’s standard data types are simple yet different from those in other languages. It is the simplicity of the language which makes it the language of choice for most applications these days.

© 2019 Sam Shepards