Data Types

Variables can hold values, and every value has a data-type. Python is a dynamically typed language; hence we do not need to define the type of the variable while declaring it. The interpreter implicitly binds the value with its type.

1. Numbers
2. Sequence Type
3. Dictionary
4. Set
5. Boolean

 


Checking type of data type

Python enables us to check the type of the variable used in the program. Python provides us the type() function, which returns the type of the variable passed.

Example:

a=10
b="Hi Python"
c = 10.5
print(type(a))
print(type(b))
print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

 


NUMBERS

Number stores numeric values. The integer, float, and complex values belong to a Python Numbers data-type.

Example:

# Intiger:
a = 5
print("The type of a", type(a))

# Float: 
b = 40.5
print("The type of b", type(b))

# Complex:
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>
The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data:

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate upto 15 decimal points.
3. Complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Numeric data type includes the conversion which is given as below:

  • Type int(x) is used to convert x to a simple integer.
  • Type long(x) is used to convert x to a long integer.
  • Type float(x) is used to convert x to a floating-point number.

 


SEQUENCE TYPE - STRINGS

The string can be defined as the sequence of characters represented in the quotation marks. In Python, we can use single, double, or triple quotes to define a string.

In the case of string handling, the operator + is used to concatenate two strings as the operation “hello”+" python" returns “hello python”.

The operator * is known as a repetition operator as the operation “Python” *2 returns ‘Python Python’.

Example1:

str = "string using double quotes"
print(str)

s = ""A multiline
string""
print(s)

Output:

string using double quotes
A multiline
string

Example2:

str1 = 'hello javatpoint' #string str1
str2 = ' how are you' #string str2
print (str1[0:2]) #printing first two character using slice operator
print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

String functions:

 


SEQUENCE TYPE - LIST

Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in the list are separated with a comma (,) and enclosed within square brackets [].

The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were working with the strings.

Accessing Elements: Accessing elements in lists is done by using Indexes. INDEX is basically the address in which the data which we want is stored.

List Slicing: Lists can be sliced. SLICING is a feature in Python which enables accessing parts of sequences like strings, lists and tuples. You can also use slicing for modifying or deleting elements of mutable data types. We can use slice [:] operators to access the data of the list.

List slicing:

sliceable[start_index:end_index:step]

*Subsetting Lists:

fruits = ["pineapple", "apple", "lemon", "strawberry", "orange", "kiwi"]
fruits[1]  # apple
fruits[0]  # "pineapple"
fruits[-1] # "kiwi"
fruits[5]  # "kiwi"
fruits[-3] # "strawberry"

# List slicing
fruits[::]    # ["pineapple", "apple", "lemon", "strawberry", "orange", "kiwi"]
fruits[0:2]   # ["pineapple", "apple"]
fruits[-2:-1] # ["orange"]
fruits[3:]    # ["strawberry", "orange", "kiwi"]
fruits[:4]    # ["pineapple", "apple", "lemon", "strawberry"]
fruits[:]     # ["pineapple", "apple", "lemon", "strawberry", "orange", "kiwi"]
fruits[::-1]  # ["kiwi", "orange", "strawberry", "lemon", "apple", "pineapple"]
fruits[::-2]  # ["kiwi", "strawberry", "apple"]
fruits[::2]   # ["pineapple", "lemon", "orange"]

# Understanding some default values
fruits[0:6:1]    # the same result as the result from fruits[::]
fruits[-1:-7:-1] # the same result as the result from fruits[::-1]

List Manipulation:

# Add values to a list
fruits.append("peach")
fruits # ["pineapple", "apple", "lemon", "strawberry", "orange", "kiwi", "peach"]
fruits = fruits + ["fig", "melon"]
fruits # ["pineapple", "apple", "lemon", "strawberry", "orange", "kiwi", "peach", "fig", "melon"]

# Change values from a list
fruits[0:2] = ["grape", "mango"]
fruits # ["grape", "mango", "lemon", "strawberry", "orange", "kiwi", "peach", "fig", "melon"]

# Delete values from a list
fruits.remove("mango")
fruits # ["grape", "lemon", "strawberry", "orange", "kiwi", "peach", "fig", "melon"]

It’s important to understand how lists work behind the scenes in Python. When you create a new list my_list, you’re storing the list in your computer memory, and the address of that list is stored in the my_list variable. The variable my_list doesn’t contain the elements of the list. It contains a reference to the list. If we copy a list with the equal sign only like this my_list_copy = my_list, you’ll have the reference copied in the my_list_copy variable instead of the list values. So, if you want to copy the actual values, you can use the list(my_list) function or slicing [:].

numbers = [10, 42, 28, 420]
numbers_copy = numbers
numbers_copy[2] = 100
numbers      # [10, 42, 100, 420]
numbers_copy # [10, 42, 100, 420]

ratings = [4.5, 5.0, 3.5, 4.75, 4.00]
ratings_copy = ratings[:]
ratings_copy[0] = 2.0
ratings      # [4.5, 5.0, 3.5, 4.75, 4.0]
ratings_copy # [2.0, 5.0, 3.5, 4.75, 4.0]

characters = ["A", "B", "C"]
characters_copy = list(characters)
characters_copy[-1] = "D"
characters      # ["A", "B", "C"]
characters_copy # ["A", "B", "D"]

Subsetting List:

x[2] results in a list, that you can subset again by adding additional square brackets.

x = [["a", "b", "c"],
     ["d", "e", "f"],
     ["g", "h", "i"]]
x[2][0]
x[2][:2]

Changing list elements:

Adding and removing elements:

Behind the scenes(1):

We’re storing a list in our computer memory and store the address of that list, so the list is in the computer memory, in x. This means that x doesn’t actually contain all the list elements, it rather contains a reference to the list. For basic operations the difference is not that important, but it becomes more so when we start copying lists.

Let’s use the example when we store the list x as a new variable y, by simply using the equals sign. Let’s now change the element with index 1 in the list y. The interesting thing is that if we now check out x again, the second element has been changed as well. That’s because when we copied x to y with the equals sign, we copied the reference to the list and not the actual values themselves. When we’re updating an element in the list, it’s one and the same list in the computer memory we’re changing. Both x and y point to this list, so the update is visible from both variables.

If we want to create a list y that points to a new list in the memory with the same values, we will need to use somehting else than the equals sign. We can use the list function. We can use list function, or slicing to select all list elements explicitly. If we now make a change to the list y points to, x is not affected.

List functions:

 


SEQUENCE TYPE - TUPLE

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses ().

A tuple is a read-only data structure as we can’t modify the size and value of the items of a tuple. They are IMMUTABLE. That means, they can’t be changed or modified further. This immutable nature makes them work more fast than lists.

Example1:

tup  = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))

#Printing the tuple
print (tup)

# Tuple slicing
print (tup[1:])
print (tup[0:1])

# Tuple concatenation using + operator
print (tup + tup)

# Tuple repatation using * operator
print (tup * 3)

# Adding value to tup. It will throw an error.
t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    t[2] = "hi";
TypeError: 'tuple' object does not support item assignment

Tuple functions:

 


DICTIONARY

Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Example 1:

# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
	
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
	
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
	
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
	
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)

Output:

Empty Dictionary:
{}

Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For'}

Example 2:

d = {1:'value','key':2}
print(type(d))

print("d[1] = ", d[1])

print("d['key'] = ", d['key'])

# Generates error
print("d[2] = ", d[2])

Output:

<class 'dict'>
d[1] =  value
d['key'] =  2
Traceback (most recent call last):
  File "<string>", line 9, in <module>
KeyError: 2

Accessing elements of Dictionary

Example 1:

# Python program to demonstrate
# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))

Output:

Accessing a element using key:
For
Accessing a element using get:
Geeks

Dictionary functions:

 


SET

A Python set is a collection just like Dictionaries and Tuples, but it is unordered with no duplicates entries.

Sets are mutable but because they are unordered, it means that there is no indexing. As a result, you can’t access or change elements inside a set.

animals = {'tiger', 'lion', 'seal', 'seal'}
# if you print animals, your set will look like this:
# {'tiger', 'lion', 'seal'}

Example:

# Creating Empty set
set1 = set()

set2 = {'James', 2, 3,'Python'}

#Printing Set value
print(set2)

# Adding element to the set

set2.add(10)
print(set2)

#Removing element from the set
set2.remove(2)
print(set2)

Output:

{3, 'Python', 'James', 2}
{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Set functions:

 


BOOLEAN

Boolean type provides two built-in values, True and False. These values are used to determine the given statement true or false. It denotes by the class bool. True can be represented by any non-zero value or ‘T’ whereas false can be represented by the 0 or ‘F’.

Example:

# Python program to check the boolean type  
print(type(True))  
print(type(False))  
print(false)  

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined