0% found this document useful (0 votes)
49 views

Data Types

The document discusses Python data types. It describes that numbers, strings, and tuples are immutable while lists, dictionaries, and sets are mutable. It provides details about each data type, including how to define them, access elements, and perform common operations like adding and removing elements.

Uploaded by

Python Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Data Types

The document discusses Python data types. It describes that numbers, strings, and tuples are immutable while lists, dictionaries, and sets are mutable. It provides details about each data type, including how to define them, access elements, and perform common operations like adding and removing elements.

Uploaded by

Python Gaming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Data type in Python

Immutable: These datatypes cannot be changed once declared.


1. Numbers,
2. Strings,
3. Tuples.

Mutable: These datatypes can be changed anytime.


4. Lists,
5. Dictionary, and
6. Sets.
1. Numbers

int To store integer values n = 20

float To store decimal values n = 20.75

To store complex numbers


complex n = 10+20j
(real and imaginary part)

bool To store boolean values flag = True


2. String
• A string is a sequence of characters enclosed within a single quote or double quote.
These characters could be anything like letters, numbers, or special symbols enclosed
within double quotation marks.
Creating a String
➢To create a string in Python we need to use either single quotes or double quotes. For
example:
String Basics
We can also use a function called len() to check the length of a string!
• Python's built-in len() function counts all of the characters in the string, including spaces and
punctuation.
String Indexing
Indexing means referring to an element of an iterable by its position within the iterable.
Each of a string’s characters corresponds to an index number and each character can be accessed
using its index number.
String Slicing
Slicing in Python is a feature that enables accessing parts of the sequence. In slicing a
string, we create a substring, which is essentially a string that exists within another string.
string[start : end : step]
start: We provide the starting index.
end: We provide the end index(this is not included in substring).
step: It is an optional argument that determines the increment between each index for
slicing.
Function Description
format() It’s used to create a formatted string from the template string and the supplied values.

Python string split() function is used to split a string into the list of strings based on a
split()
delimiter.

Python String count() function returns the number of occurrences of a substring in the
count()
given string.

strip() Used to trim whitespaces from the string object.

upper() We can convert a string to uppercase in Python using str.upper() function.

lower() This function creates a new string in lowercase.

Python string replace() function is used to create a new string by replacing some parts
replace()
of another string.

Python String find() method is used to find the index of a substring in a string.
find()
3. Tuple
• Tuples are ordered collections of heterogeneous data that are unchangeable and
Contains Duplicates.
• Using parenthesis (): A tuple is created by enclosing comma-separated items inside
rounded brackets.
tuple = (10, 20, 25.75)
print(tuple)
• We can find the length of the tuple using the len() function. This will return the number
of items in the tuple.
print(len(tuple))
• We can access an item of a tuple by using its index number inside the index
operator [] and this process is called “Indexing”.
Adding and changing items in a Tuple
• A list is a mutable type, which means we can add or modify values in it, but tuples are
immutable, so they cannot be changed.
• Also, because a tuple is immutable there are no built-in methods to add items to the
tuple.
• We can convert the tuple to a list, add items, and then convert it back to a tuple. As
tuples are ordered collection-like lists the items always get added in the end.

Removing items from a tuple


Tuples are immutable so there are no pop() or remove() methods for the tuple. We can
remove the items from a tuple using the following two ways.
• Using del keyword (The del keyword will delete the entire tuple.)
• By converting it into a list.
t1 = (10, 20, 30, 40, 50) and t2 = (60, 70, 80, 60)
Operation Description
t1 + t2 Cncatenate the tuples t1 and t2. Creates a new tuple containing the items from t1 and t2.
t1 * 5 Repeat the tuple t1 5 times.
t1[i] Get the item at the index i. Example, t1[2] is 30
Tuple slicing. Get the items from index i up to index j (excluding j) as a tuple. An example t1[0:2] is (10,
t1[i:j]
20)
Tuple slicing with step. Return a tuple with the items from index i up to index j taking every kth item.
t1[i:j:k]
An example t1[0:4:2] is (10, 30)
len(t1) Returns a count of total items in a tuple

t2.count(60) Returns the number of times a particular item (60) appears in a tuple. Answer is 2

t1.index(30) Returns the index number of a particular item(30) in a tuple. Answer is 2

min(t1) Returns the item with a minimum value from a tuple


max(t1) Returns the item with maximum value from a tuple
4. List
• List are ordered collections of heterogeneous data that are changeable and
Contains Duplicates.
Creating a Python list
➢Using list() constructor: In general, the constructor of a class has its class name.
Similarly, Create a list by passing the comma-separated values inside the list().
a = list((1, 2 ,3 , ’ABC’))
type(a)
➢Using square bracket ([]): In this method, we can create a list simply by enclosing
the items inside the square brackets.
b = [1, 2, 3, 2, 1]
Accessing items of a List
➢Using indexing, we can access any item from a list using its index number.
➢Using slicing, we can access a range of items from a list.
Adding elements to the List
• We can add a new element to the list using the list methods such as
➢append() accepts only one parameter and adds it at the end of the list.
➢insert() add the object/item at the specified position (i.e index number) in the list.
insert(index, object)
➢extend(). The extend method will accept the list of elements and add them at the
end of the list. We can even add another list by using this method.
list = list([5, 8, 'Tom', 7.50])
list.extend([25, 75, 100])
Removing elements from a List

remove(item) To remove the first occurrence of the item from the list.

pop(index) Removes and returns the item at the given index from the list.

clear() To remove all items from the list. The output will be an empty list.
There are some built-in methods that you can use on lists.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
5. Dictionary
• Dictionary items are unordered, changeable, and do not allow duplicates key.
• Dictionary items are presented in the pair of key: value and can be referred to by
using the key name.
Creating a dictionary
The dictionaries are created by enclosing the comma-separated Key: Value pairs inside the {}
curly brackets. The colon ‘:‘ is used to separate the key and value in a pair.
student1 = {"name": “abc", "class": “BCADS", “Roll no":2022}
• A dictionary value can be of any type, and duplicates are allowed in that.
• Keys in the dictionary must be unique and of immutable types like string, numbers, or
tuples.
Accessing elements of a dictionary
There are two different ways to access the elements of a dictionary.
• Retrieve value using the key name inside the [] square brackets
print(student['name'])
• Retrieve value by passing key name as a parameter to the get() method of a dictionary.
print(student.get(‘name’))

keys() Returns the list of all keys present in the dictionary.


values() Returns the list of all values present in the dictionary
Returns all the items present in the dictionary. Each
items()
item will be inside a tuple as a key-value pair.
Adding items to the dictionary
We can add new items to the dictionary using the following two ways.
Using key-value assignment: Using a simple assignment statement where value can be
assigned directly to the new key.
person["weight"] = 50
Using update() Method: In this method, the item passed inside the update() method will be
inserted into the dictionary. The item can be another dictionary or any iterable like a tuple of
key-value pairs.
person.update({"height": 6})
Join two dictionary
dict1 = {‘abc': 70, ‘def': 80, ‘ghe': 55}
dict2 = {‘ijk': 68, ‘lmn': 50, ‘opq': 66}
dict1.update(dict2)
Removing items from the dictionary
Return and removes the item with the key and return its value. If the key is not found, it
pop(key[,d]) raises KeyError.

Return and removes the last inserted item from the dictionary. If the dictionary is empty,
popitem() it raises KeyError.

del key The del keyword will delete the item with the key that is passed

clear() Removes all items from the dictionary. Empty the dictionary

del dict_name Delete the entire dictionary

Sort dictionary
dict1 = {'c': 45, 'b': 95, 'a': 35}
print(sorted(dict1.items()))
print(sorted(dict1))
print(sorted(dict1.values()))
d1 = {'a': 10, 'b': 20, 'c': 30} and d2 = {'d': 40, 'e': 50, 'f': 60}
Operations Description
dict({'a': 10, 'b': 20}) Create a dictionary using a dict() constructor.
d2 = {} Create an empty dictionary.
d1.get('a') Retrieve value using the key name a.
d1.keys() Returns a list of keys present in the dictionary.
d1.values() Returns a list with all the values in the dictionary.

d1.items() Returns a list of all the items in the dictionary with each key-value pair inside a tuple.

len(d1) Returns number of items in a dictionary.


d1['d'] = 40 Update dictionary by adding a new key.
d1.update({'e': 50, 'f': 60}) Add multiple keys to the dictionary.
d1.pop('b') Remove the key b from the dictionary.
d1.popitem() Remove any random item from a dictionary.
d1.clear() Removes all items from the dictionary.
6. Set
• A set is an unordered, Partially Heterogeneous collection of unique data items.
In other words, Python Set is a collection of elements (Or objects) that contains
no duplicate elements.
• Creating a Set
➢ Using curly brackets: Creating a Set is by just enclosing all the data items inside the curly
brackets {}. The individual values are comma-separated.
set1 = {‘abc', ‘5+4', 25, 75.25}
print(set1)
➢Using set() constructor:
list1 = [20, 30, 20, 30, 50, 30]
set2 = set(list1)
print(set2)
Accessing items of a set
The items of the set are unordered and they don’t have any index number. In
order to access the items of a set, we need to iterate through the set object using a
for loop.
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
Adding items to a Set
1. add() method: The add() method is used to add one item to the set.
Set 1 = {1, 2, 3, 4, 5, 6}
set1.add(9)
2. Using update() Method: The update() method is used to multiple items to the Set. We need to pass the
list of items to the update() method
set1.update([10,20,30])
print(set1)
Removing items from Set
To remove a single item from a set. This method will take one parameter, which is the item to be
remove()
removed from the set. Throws a keyerror if an item not present in the original set
To remove a single item that may or may not be present in the set. This method also takes one
discard() parameter, which is the item to be removed. If that item is present, it will remove it. It will not throw
any error if it is not present.
pop() To remove any random item from a set

clear() To remove all items from the Set. The output will be an empty set

del set Delete the entire set

remove() vs discard()
The remove() method throws a keyerror if the item you want to delete is not present in a set.
The discard() method will not throw any error if the item you want to delete is not present in a set.
Type conversion
1. int(a base): This function converts any data type to an integer. ‘Base’ specifies the base in
which the string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
3. tuple() : This function is used to convert to a tuple.
4. set() : This function returns the type after converting to set.
5. list() : This function is used to convert any data type to a list type.
6. dict() : This function is used to convert a tuple of order (key, value) into a dictionary.
7. str() : Used to convert an integer into a string.

You might also like