Python – Variable Types

Variables are nothing more than memory spaces reserved for storing values. It means that when a variable is created, some memory space is reserved.

Based on the variable data type, the interpreter allocates memory and determines what can be stored in the reserved memory. Thus, by assigning different data types to variables, you can store integers, decimal numbers, or characters in these variables.

Assigning values to variables

It is not necessary to explicitly declare Python variables to reserve memory. They are declared automatically when a variable is assigned a value. The equality sign (=) is used to assign values to variables.

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

#!/usr/bin/python

number = 80          # An integer assignment
price = 69.2         # A floating point
name  = "Mike"       # A string

print number
print price
print name

Here 80, 69.2, and “Mike” are the values assigned to the variable number, price, and name. This leads to the following result –

80
69.2
Mike

Multiple-use

Python allows you to assign one value to several variables simultaneously. For example…

x = y = z = 7

Here, an entire object with a value of 7 is created and the same memory area is assigned to these three variables. You can also assign several objects to several variables. For example…

x,y,z = 27,42,"Mili"

Variable x and y are assigned two integer objects with values 27 and 42, and variable z is assigned a string object with value “Mili”.

Standard data types

The data stored in the memory can be of different types. For example, a person’s age is stored as a numeric value and their address as an alphanumeric character. There are several standard data types on Python that are used to define the operations that can be performed on it and the storage method for each of these data types.

Python has five standard data types –

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

Python numbers

Numerical data types store numerical values. Numerical objects are created when a value is assigned to them. For example…

vara = 3
varb = 8

The reference to a numeric object can also be deleted with a del statement. The syntax for del declarations –

del vara[,varb[,varc[....,varz]]]]

With the Del declaration, you can delete one or more objects. For example…

del var
del vara, varb

Python supports four different numeric types –

int (signed integers)
long (long integers, octal, and hexadecimal can also be displayed).
floating number (floating point real values)
complex (complex numbers)

Examples.

Here are a few examples of numbers –

intlongfloatcomplex
1151924361L0.03.14j
109-0x19323L15.2045.j
-7550122L-21.99.322e-36j
1800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0500535633629843L-90.0-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

    Python allows using small L with length, but it is recommended to use only large L to avoid confusion with number 1. Python shows long integers with large L.

    A complex number consists of an ordered pair of real floating point numbers denoted by x + yj, where x and y are real numbers, and j is an imaginary unit.

python strings

A string is identified in Python as a contiguous set of characters that appear in quotation marks. Python allows the use of single or double quote pairs. String subsets can be taken using the trim operators ([ ] and [:] ), with indexes starting at 0 at the beginning of the string and accumulating at -1 at the end.

The plus sign (+) is the string concatenation operator, and the asterisk (*) is the repetition operator. For example, –

#!/usr/bin/python

stra = 'Hello How are you?'

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

This will lead to the following result…

Hello How are you?
H
llo
llo How are you?
Hello How are you?Hello How are you?
Hello How are you?Mili

python lists

Lists are the most universal types of composite data on Python. A list contains elements separated by commas and enclosed in square brackets ([]). To some extent, lists are similar to C sets. One difference is that all elements belonging to a list can be of different data types.

The values stored in the list can be accessed using the slice operators ([ ] and [:]), with the indexes starting with 0 at the beginning of the list and ending with -1. The plus sign (+) is the list concatenation operator, and the asterisk (*) is the repeating operator. For example, –

This leads to the following result…

#!/usr/bin/python

list = ['xyz', 69 , 12,20, 'Mili', 15.3]
lista = [230, 'Harry']

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 lista * 2     # Prints list two times
print list + lista  # Prints concatenated lists

This produce the following result −

['xyz', 69 , 12,20, 'Mili', 15.3]
xyz
[69 , 12,20]
[12,20, 'Mili', 15.3]
[230, 'Harry, 230, 'Harry]
['xyz', 69 , 12,20, 'Mili', 15.3, 230, 'Harry]

Python’s tuples

A motorcade is another type of sequence data similar to a list. A motorcade consists of a series of values separated by commas. However, in this case as well.

Main differences between lists and tuples: lists are enclosed in brackets ( [ ] ) and their elements and dimensions can be changed, while tuples are enclosed in brackets ( ( ) ) and cannot be updated. Tuples can be read-only lists. For example –

#!/usr/bin/python

tuple = ('xyz', 69 , 12,20, 'Mili', 15.3)
tuplea = (230, 'Harry')

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

It gives the following result –

('xyz', 69 , 12,20, 'Mili', 15.3)
xyz
(69 , 12,20)
(12,20, 'Mili', 15.3)
(230, 'Harry, 230, 'Harry)
('xyz', 69 , 12,20, 'Mili', 15.3, 230, 'Harry)

The following code is not valid for the tuple because we tried to update the tuple, which is prohibited. A similar case is possible with lists –

#!/usr/bin/python

tuple = ('xyz', 69 , 12,20, 'Mili', 15.3)
list = ['xyz', 69 , 12,20, 'Mili', 15.3]
tuple[2] = 1000    # Invalid syntax with tuple
list[2] = 1000     # Valid syntax with list

Python Dictionary

Python dictionaries are a kind of hash table. They function as associative arrays or hashes that are found in Perl and consist of pairs of key values. The dictionary key can be almost any Python type, but they are usually numbers or strings. The values, however, can be any arbitrary Python object.

Dictionaries are enclosed in curly brackets ({ }), and values can be assigned and accessed using square brackets ([]). For example – ([].

#!/usr/bin/python

dict = {}
dict['one'] = "This is 1st"
dict[6]     = "This is 2nd"

dict1 = {'name': 'Mili','price':271, 'study': 'science'}

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

It gives the following result –

This is 1st
This is 2nd
{'name': 'Mili','price':271, 'study': 'science'}
['name','price', 'study']
['Mili',271,'science']

There is no notion of order among the elements of dictionaries. It is wrong to say that the elements are “not in order”, they are simply not ordered.

Data Type Conversion

Sometimes it may be necessary to perform a conversion between the built-in types. To convert between types, simply use the type name as a function.

There are several built-in functions to convert one data type to another. These functions return a new object representing the converted value.

Sr.No.Function & Description
1int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
2long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
3float(x) Converts x to a floating-point number.
4complex(real [,imag]) Creates a complex number.
5str(x) Converts object x to a string representation.
6repr(x) Converts object x to an expression string.
7eval(str) Evaluates a string and returns an object.
8tuple(s) Converts s to a tuple.
9list(s) Converts s to a list.
10set(s) Converts s to a set.
11dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
12frozenset(s) Converts s to a frozen set.
13chr(x) Converts an integer to a character.
14unichr(x) Converts an integer to a Unicode character.
15ord(x) Converts a single character to its integer value.
16hex(x) Converts an integer to a hexadecimal string.
17oct(x) Converts an integer to an octal string.