Python – Data Types

Variables

Data in programming is stored in containers called variables. Every value(variable) in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set. You can let python determine the data type or you can explicitly set it.

Data Types

Text Type str
Numeric Types: intfloatcomplex
Sequence Types: listtuplerange
Mapping Type: dict
Set Types: setfrozenset
Boolean Type: bool
Binary Types: bytesbytearraymemoryview

 

str data type

In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or more characters put in a single quote, double-quote or triple quote. In python there is no character data type, a character is a string of length one. It is represented by str class.

firstName = "Folau"
print(firstName)

firstName = str("Folau")
print(firstName)

# console
Folau
Folau

int data type

Integers can be of any length, it is only limited by the memory available. It contains positive or negative whole numbers (without fraction or decimal)

intNum = 2
print(intNum)

num = int(2)
print(num)

float data type

A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

number = 2.5
print(number)

num = float(2.5) 
print(numb)

#console
2.5
2.5

complex data type

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

list data type

List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type.

lista = [1, 2.2, 'python']
print(lista)

listb = list((1, 2.2, 'python'))
print(listb)
# console
[1, 2.2, 'python']
[1, 2.2, 'python']

tuple data type

Tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

# how to create tuple
tuple_numbers = (1, 2, 3, 1)
tup = 1, 2, 3, 1, None, "Hello"
nested_tuple = ((1, 2), ("Hello", "Hi"), "Python")
empty_tuple = ()
numbs = tuple((1,2,3))
# how to access tuple elements
nested_tuple = (1, 2, (3, 4), (5, 6, 7))
nested_tuple[2][0] -> 3

range data type

range returns a sequence of numbers starting from 0 and increments to 1 until it reaches a specified number. The most common use of range function is to iterate sequence type. It is most commonly used in for and while loops. We can use range in python to increment and decrement step values using positive and negative integers.

# range(start, stop, step)
# start - where to start from
# stop - where to stop
# step - how big of a step for each iteration

evenNumbers = range(2, 20 ,2)
for num in evenNumbers:
    print(num)

#console
2
2
4
6
8
10
12
14
16
18

dict data type
Dictionary  is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type.

person = {"firstName":"Folau", "lastName":"Kaveinga"}
print(person)

user = dict(firstName="Folau", lastName="Kaveinga")
print(user)

set data type

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.

# set
numbers = set((1,2,3))
print(type(numbers))

numbers = {1, 2, 3}
print(type(numbers))

fronzenset data type

Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, elements of the frozen set remain the same after creation. Due to this, frozen sets can be used as keys in Dictionary or as elements of another set. But like sets, it is not ordered (the elements can be set at any index).

# tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')

fSet = frozenset(vowels)
print('The frozen set is:', fSet)
print('The empty frozen set is:', frozenset())

# frozensets are immutable
fSet.add('v') -> error

boolean data type

True or False. Boolean objects that are equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the class bool. Note that True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

isMale = True
print(isMale)

# console
True

bytes data type

The bytes() method returns a immutable bytes object initialized with the given size and data. bytes() method returns a bytes object which is an immutable (cannot be modified) sequence of integers in the range 0 <=x < 256. The syntax of bytes() method is

bytes([source[, encoding[, errors]]])
string = "My name is Folau"

# string with encoding 'utf-8'
arr = bytes(string, 'utf-8')
print(arr)

#console
b'My name is Folau'

bytearray data type

The bytearray() method returns a bytearray object which is an array of the given bytes. bytearray() method returns a bytearray object which is mutable (can be modified) sequence of integers in the range 0 <= x < 256. The syntax of bytearray() method is

bytearray([source[, encoding[, errors]]])
string = "My name is Folau"

# string with encoding 'utf-8'
arr = bytearray(string, 'utf-8')
print(arr)

#console
bytearray(b'My name is Folau')

memoryview data type

The memoryview() function returns a memory view object of the given argument. A memory view is a safe way to expose the buffer protocol in Python. It allows you to access the internal buffers of an object by creating a memory view object. To expose the buffer protocol using memoryview(), we use this syntax:

memoryview(obj)
#random bytearray
random_byte_array = bytearray('ABC', 'utf-8')

mv = memoryview(random_byte_array)

# access memory view's zeroth index
print(mv[0])

# create byte from memory view
print(bytes(mv[0:2]))

# create list from memory view
print(list(mv[0:3]))

#console
65
b'AB'
[65, 66, 67]

 

 

The data type is set when you assign a value to a variable.

numbers = {1, 2, 3}
print(type(numbers))

# console
<class 'set'>

Explicitly declaring a data type. I found this very useful when reading other people’s code.

numbers = set((1,2,3))

Use type() function to find out a data type.

numbers = set()
numbers.add(1)
numbers.add(2)
numbers.add(3)
print(type(numbers))

# console
<class 'set'>

Use isinstance function to check if an object belongs to a particular class or type

number = 2.5
print(number, "is float number?", isinstance(number,float))

#console
2.5 is float number? True

 

Source code on Github




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published.