Different Types of Variables in Python with Examples

Types of Variables in Python

Variable Types in Python 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.

These are some of the common types of variables in Python.

Variable TypeDescriptionExample
IntegerStores whole numbers without decimal pointsage = 30
FloatStores decimal numberspi = 3.14
StringStores sequences of charactersname = “Mary”
BooleanStores either True or Falseis_valid = True
ListStores an ordered collection of itemsnumbers = [1, 2, 3, 4]
TupleStores an ordered collection of items (immutable)point = (5, 10)
DictionaryStores key-value pairsperson = {“name”: “Mary”, “age”: 30}
SetStores an unordered collection of unique itemsunique_numbers = {1, 2, 3, 4}

Assigning Values to Variables

Assigning values to variables in Python is a fundamental concept. It allows you to store and manipulate data within your code.

To assign a value to a variable, you can use the assignment operator “=”.

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

In Python, you can assign values to multiple variables in a single line using multiple assignments.

This allows concise assignment to multiple variables simultaneously.

For instance:

# Multiple assignment
x = y = z = 1

In this case, we’re creating an integer object of type 1 and setting all three variables to the same address in memory.

Multi-object assignments to multiple variables are also supported.

For 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

In Python, there are different types of variables that you can use to store and manipulate data.

Here are some common 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.

For 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 a 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

Python strings are a data type used to represent sequences of characters. They are enclosed in single (‘ ‘) or double (” “) quotes.

Also, in Python, you can extract parts of strings using the slice operator ([] and [:]) and index positions that range from 0 to -1.

Moreover, 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

Output:

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 ([]).

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

Python tuple is an ordered collection of elements, similar to a list.

However, tuples are immutable, meaning their values cannot be changed once assigned.

Tuples are created by enclosing items in parentheses ( ) and separating them with commas.

For example:

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')

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.

For example:

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']

How to check the type of variable in Python

You can check the type of a variable in Python, using the built-in type() function. The type() function returns the data type of the specified variable.

Here’s an example of how to use the type() function to check the type of a variable:

# Integer
age = 25
print(type(age))  # <class 'int'>

# Float
pi = 3.14
print(type(pi))  # <class 'float'>

# String
name = "John"
print(type(name))  # <class 'str'>

# Boolean
is_valid = True
print(type(is_valid))  # <class 'bool'>

# List
numbers = [1, 2, 3, 4]
print(type(numbers))  # <class 'list'>

In the above examples, the type() function is called with the variable as an argument, and it returns the corresponding data type enclosed in.

Summary

In summary, we explored the Types of Variables in Python which is a reserved memory space. Also, we learned how to assign variables, including multiple Assignments.


1 thought on “Different Types of Variables in Python with Examples”

Leave a Comment