Different Types of Variables in Python with Examples

Types of Variables in Python

In this Python tutorial, you will learn about the Types of Variables in Python. Variable Types are just reserved memory spaces for storing values. This means that when you create a variable, you reserve memory space.

Python is entirely object-oriented and is not “statically typed.” You do not need to declare variables or declare their type before utilizing them. Every Python variable is an object.

Data types in Python represent the kind of value that can be stored in a variable. In Python, everything is an object, so data types are actually classes, and variables are instances of these classes.

Assigning Values to Variables

In these Python Variable Types, Python variables don’t need to be explicitly declared to take up space in memory. When you give a value to a variable, the declaration is done automatically. The equal sign (=) is used to tell variables what their values are.

The name of the variable is the operand to the left of the = operator, and the value stored in the variable is the operand to the right of the = operator. For instance,

#!/usr/bin/python

number = 100          # An integer assignment
score   = 98.5          # A floating point
name    = "Prince"          # A string

print counter
print miles
print name

In this case, the values for the counter, miles, and name variables are 100, 98.5, and “Prince”, respectively. This causes the following to happen:

100
98.5
Prince

Multiple Assignment

You can give the same value to several variables at the same time in Python. For instance,

# Multiple assignment
x = y = z = 1

In this case, we’re creating an integer object of type 1 and set all three variables to the same address in memory. Multi-object assignments to multiple variables are also supported. As an example,

# Multiple assignment to multiple variables
x,y,z = 1,2,"prince"

Here, the variables x and y are given the values 1 and 2, respectively, and the variable z is given the value “prince” from a string object.

Different Types of Variables in Python

Python has different types of variables that can be stored in memory. For example, a person’s age is saved as a number, and his or her address is saved as a string of letters and numbers. Python has a number of standard data types that are used to describe how they can be used and how they are stored.

Python comes with different types of variables:

1. Python Numbers

In Python, the Numbers variable type or data type holds values that number. You make a number object when you give it a value. As an example,

var1 = 1
var2 = 10

You can also use the del statement to remove the reference to a number object. The del statement’s syntax is

#del statement
del var1[,var2[,var3[....,varN]]]]

The del statement lets you delete a single object or a group of objects. For instance,

del var
del var_a, var_b

Python can work with four different kinds of numbers.

  • int (signed integers)
  • long (long integers, they can also be represented in octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)

Examples

Here are some examples of the numbers:

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j
Kinds of numbers in Python
  • Python lets you use a lowercase l with long, but you should only use an uppercase L to avoid getting confused with the number 1. Python shows long numbers with the capital letter L.
  • A complex number is made up of two real floating-point numbers in the right order. It is written as x + yj, where x and y are the real numbers and j is the imaginary unit.

2. Python Strings

In Python, the string is a type of variable that holds a group of characters together. This is shown by the quotation marks and Python lets you use either single or double quotes in pairs. Using the slice operator ([] and [:]) and indexes that start at 0 at the beginning of the string and end at -1 at the end, you can take parts of strings.

The plus sign (+) is used to join strings together, and the asterisk (*) is used to repeat something. For instance,

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string

This will lead to the following result:

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

3. Python Lists

Python Lists are the most useful compound variable type. The items in a list are separated by commas and put inside square brackets ([]). One difference is that all of the items in a list can have different data types.

Using the slice operator ([] and [:]), you can get to the values in a list. The indexes start at 0 at the beginning of the list and go all the way to -1 at the end. The plus (+) sign is the operator for joining lists together, and the asterisk (*) is the operator for repeating something. For instance,

list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print list          # Prints complete list
print list[0]       # Prints first element of the list
print list[1:3]     # Prints elements starting from 2nd till 3rd 
print list[2:]      # Prints elements starting from 3rd element
print tinylist * 2  # Prints list two times
print list + tinylist # Prints concatenated lists

This leads to the following:

['abcd', 786, 2.23, 'john', 70.2]
abcd
[786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

4. Python Tuples

A Python tuple is another type of sequence data that works as a list. A tuple is a group of values that are split up by commas and enclosed in parentheses.

The main differences between lists and tuples are that lists are surrounded by brackets ([]) and their elements and size can be changed, while tuples are surrounded by parentheses (()) and cannot be changed. You can consider tuples to be similar to read-only lists in this regard. For instance,

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
tinytuple = (123, 'john')

print tuple               # Prints the complete tuple
print tuple[0]            # Prints first element of the tuple
print tuple[1:3]          # Prints elements of the tuple starting from 2nd till 3rd 
print tuple[2:]           # Prints elements of the tuple starting from 3rd element
print tinytuple * 2       # Prints the contents of the tuple twice
print tuple + tinytuple   # Prints concatenated tuples

This leads to the following:

('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2, 123, 'john')

The following code is not valid for tuple because we tried to update a tuple, which will report an error. Lists can be used in a similar way.

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2  )
list = [ 'abcd', 786 , 2.23, 'john', 70.2  ]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list

5. Python Dictionary

The Python Dictionary is kind of like hash tables. They are made up of key-value pairs and work like associative arrays or hashes in Perl. A dictionary key can be almost any type in Python, but numbers and strings are the most common. The opposite is true for values, which can be any Python object.

Class dict is the dict object of Python, if you want to know more about dictionaries you may visit Python’s Built-in Types.

Curly braces ({}) surround dictionaries, and square braces can be used to assign and get values from dictionaries ([]). For instance,

dict = {}
dict['one'] = "This is one"
dict[2]     = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print dict['one']       # Prints value for 'one' key
print dict[2]           # Prints value for 2 key
print tinydict          # Prints complete dictionary
print tinydict.keys()   # Prints all the keys
print tinydict.values() # Prints all the values

This leads to the following:

This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']

There is no order to the words in a dictionary. You cannot claim that the elements are “out of order;” rather, they are not arranged in any specific fashion.

Summary

In summary, you will learn about the Types of Variables in Python. And in this tutorial, we talked about the following: Assigning Variables, and Multiple Assignment. I hope you learn a lot about the types of variables in Python.

In the next tutorial, you will learn about the Python Basic Operators. I hope that these Python Types of Variables help you understand how to write and execute a Python program.


Leave a Comment