Python – Data Types

Data Types in Python

The Python programming language provides a set of data types that can be used to define a variable. Memory is allocated for a variable based on the data type of the variable. This is because, data types have different sizes which is in bytes.


Variable Declaration

Python does not provide an explicit way to declare a variable. It uses implicit variable declaration. For instance in language like Java, you must declare a variable before you can assign it a value.

In Python, the variable declaration is done automatically when a variable is assigned a value using the assignment operator (=). The examples below show variable assignment (with implicit declaration).

# Assignment and implicit data type declaration in Python
index = 10              # An integer data type
distance = 500.05       # A floating point data type
firstname = "Kindson"   # A string data
scores = [67,87,98,54,82] # A list data type

print(index)
print(distance)
print(firstname)

In the above program, index is an integer type, distance is a floating point type while firstname is a string type. If you run the above code, you will have :

10 
500.05 
Kindson

Multiple Assignments

A unique feature of Python is that it allows you to assign a value to more than one variable in the same line. This is accomplished using the code below:

x = y = z = 200
score = average = 89.9

In the first line three assignments was made. 200 is assigned to x, assigned to y, and assigned to z. This is equivalent to :

x = 200
y = 200
z = 200

In the second line score is assigned a value of 89.9 and average is assigned a value of 89.9 as well

Another way to achieve multiple assignment is to assign different values to different variables in the same. For the example below, name is assigned a value Kindson, score is assigned a value of 100 and age is assigned a value 36

name, score, age = "Kindson", 100, 36

You simply use comma to separate the variable names and the values and then the variables are assigned receptively.


Python Standard Data Types

The Python Programming Language provided inbuilt data types which a have standard memory size associated with them. The 5 Python standard data types we are going to consider includes:

  • Numbers
  • String
  • Lists
  • Tuples
  • Dictionary

Numbers in Python

Numbers are data types used to store numeric values. To use a number data type simply assign a number to the variable.

score = 89.4
total = 200

The above code create two number variables, score and total and assigns them values

Python provides a function to delete reference to a number variable that has been created. This is done using del keyword. For example:

del score
del total
del x, y, z

The four different number types provided by Python are:

  • int – signed or unsigned integer values
  • long – long integers
  • float – floating point values
  • complex – complex numbers having a real and imaginary parts

The table below give a summary of

int long float complex
300 8976576L 0.45 5.56j
55 -0x29656L 45.20 63.j
-524 055L -52.8 5.087e-24j

 


Python Strings

In Python, strings are identified as a set of characters enclosed in quotes, which may be either single or double quotes. Substrings of a particular string can be formed using the slice operator [ ] and [:].

A substring is specified with index staring from 0 for the first character of the string. A index of -1 is also used to indicate the last character on the string.

Two strings can be joined together using the concatenation operator (+). Strings can be repeted or multiplied using the repetition operator (*). Lets take some examples:

word = "Python Programming"
print(word)              # Prints out the entire string
print(word[0])           # Prints the first character in the string
print(word[3:6])         # Print the 4th to the 7th character
print(word[3:]           # Prints the 4th to the last character
print(word + " Tutorial" # Attaches Tutorial to the end of the string
print(word * 3)          # Prints the string 3 times

Python Lists

Lists are part of Python collection data types. A list in Python contains different values separated by comma and enclosed in square braces []. Items in a list could be of the same or of different data types.

Just like in strings, individual elements of a list can be accessed using the slice operator [ ] or [ ]. Starting from the first element of the list, the index is 0. Starting from the last element, the index is -1.

The concatenation operator (+) and the repetition operator (*) applies in list just like in strings. The program code below illustrates the use of lists in Python.

list1= [ 'wxyz', 0.85, 52, '100', 780.2 ]
list2 = [999, 'Kindson']

print(list1)         # Prints whole list
print(list1[0])      # Prints first item in of the list
print(list1[1:4])     # Prints elements beginning from 2nd till 5th 
print(list1[2:])     # Prints elements beginning from 3rd element
print(list2 * 2)      # Prints list twice
print(list1 + list2)  # Combines bot list1 and list2

If the above code is executed, the output would be:

[ 'wxyz', 0.85, 52, '100', 780.2 ]
wxyz
[0.85, 52, '100', 780.2]
[52, '100', 780.2]
[999, 'Kindson'999, 'Kindson']
['wxyz', 0.85, 52, '100', 780.2, 999, 'Kindson' ]

Python Tuples

Tuples in Python are similar to lists with the following two difference:

  • Tuples are specified using rounded brackets (). Not square braces!.
  • Tuples are immutable – this means that items in a tuple cannot be modified.

Let’s take some examples

tuple1= ( 'wxyz', 0.85, 52, '100', 780.2 )
tuple2= (999, 'Kindson')

Every other operations that apply to a list applies to a tuple. But take not that the operations below would succeed in a list but would generate an error in a tuple.

list1[0] = 'abcd'      # Would succeed because lists a mutable
tuple1[0] = 'abcd'     # The would fail because tuples are immutable

 


Python Dictionary

Python Dictionary are used to store key value pairs just like in a hash table. Each entry in a dictionary has a key and a value. Keys and values in a dictionary can be of any type.

A typical example of a dictionary in Python is the days of the week where each week day is assigned a number each corresponding to the day name. This is shown below

weekdays = {
1: "Monday",
2: "Tuesday",
3: "Wednesday",
4: "Thursday",
5: "Friday",
6: "Saturday",
7: "Sunday"
}

The following operations are all valid for a dictionary in Python:

print(weekdays[1])       # Prints Monday
print(weekdays)          # Prints the complete dictionary
print(weekdays.keys())   # Prints all the keys, 1, 2, 3,4,5,6,7
print(weekdays.values()) # Prints all the values: Monday, . . , Sunday

Data Type Conversion in Python

Python provides functions needed to convert between the data types. For example, you may want to covert a user input in string to an integer to be able to use it for calculation. The table below gives a list of Python data type conversion functions

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