Exploring Different Data Types in Python: A Comprehensive Overview | Python Journey

Data Types in Python:

In Python, data types define what value a variable can hold and what operations can be performed on that value. Python supports many built-in data types including arithmetic types (such as integers, floating point numbers, and complex numbers), sequence types (such as strings, lists, and tuples), mapping types (such as dictionaries), and set types (such as sets and frozen sets). Each data type serves a different purpose; For example, integers are used for whole numbers, floats for decimal numbers, and strings for text data. Understanding data types is key to writing effective and error-free codes, as it ensures proper use of data and use of the program.




Learning Objectives:

DATA HANDLING

Data Types

  • Python Numbers
  • Python Strings
  • Python Booleans
  • Mutable and Immutable
  • Python Lists
  • Python Tuples
  • Python Dictionaries
  • Sets
  • FrozenSet


  • Python Numbers:

There are three types of numeric types: int, float, and complex.

Example:

x = 1    # int
y = 2.8  # float
z = 1j   # complex

To verify the type of any object in Python, use the type() function:

Example:

print(type(x))
print(type(y))
print(type(z))


Integer:

An integer in Python is an entire variety with out a fractional factor. It can be positive, negative, or zero. Python are of type int and have no size limit, letting them grow as huge as the memory lets in. Examples of integers consist of 3, -forty two, and zero.

Example:




Float:

A float in Python  has a decimal point. It represents real numbers and can be used to carry out mathematics operations that require precision. Floats are of type float.


Example:






Complex:
In Python, a complex number is a number that has a real and an imaginary object. It is represented as a + bj, where a is the real part and b is the imaginary part. The Complex numbers are Complex.

Example:







  • Python String:
In Python, a string is a sequence of characters enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """). Strings are used to represent text and can be letters, numbers, symbols, and white space.

'hello' is the same as "hello".
Example:





Quotes Inside Quotes

You can use quotes inside a string, as long as they don't match the quotes surrounding the string:

Example:






Assign String to a Variable

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

Example:






  • Python Booleans:
A Boolean in Python is a data type that can have one of two values: True or False. Booleans are often used in conditional statements and expressions to control the flow of a program.

Exmple:






  • Mutable and Immutable in Python:

Mutable:

Mutables in Python are what can be manipulated after they are created. This means you can change their content, add or remove elements, or change their state without creating a new item. Common examples of mutable objects are lists, dictionaries, and sets. For example, you can change some items in a list or update key-value pairs in a dictionary. Updates are useful when you need to change a lot of data structures in your code.

Immutable:

But immutable things, once created, cannot be changed. Any action that changes an object without changing the value will result in the creation of a new object. Examples of immutable objects in Python include strings, tuples, and integers. For example, if you try to modify a string or tuple, Python will create a new object with the updated value instead of replacing the original object. Updates are useful for ensuring data integrity, especially when objects are used as keys in a dictionary or when concurrency is a concern

  • Python Lists:

In Python, a list is a sequence of objects that can store various types of data, including numbers, strings, and even other lists. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuples, Set and Dictionary all with different qualities and usage. Tables are defined by items enclosed in square brackets ([]), each item separated by a comma. 

They are versatile and widely used due to their dynamic resizability, allowing features to be added, removed or changed. Lists are dynamic, which means they can change their elements where without creating a new list. These variables provide lists data structures needed to handle related data collection in Python, whether for simple tasks such as storing numbers in sequence or complex operations such as algorithms and data processing pipelines they will be used.

Example:

Creating a List:


List Items:

In Python, a list is a collection of objects that can contain data types such as integers, strings, and other lists. Each item in the list is an element, and the elements can be referred to by their index, starting with zero for the first element.

Example:





Ordered:

Lists are ordered collections of objects, meaning that objects are in a defined order. When you create a list, items are stored in the order you define. This system is maintained and can be used to access objects through their index.

Example:



Changeable:

Lists are dynamic, which means you can change their content after they’ve been created. You can add, remove, or modify list items. This transformation makes the list a more convenient data structure for planning tasks.

Example:



Allow Duplicates:

Since lists are indexed, lists can have items with the same value:

Example:


List Length:

To determine how many items a list has, use the len() function:

Example:
List Items - Data types:

List items can be of different types.
String, int and boolean data types;

Example:




Access List items:

List items are indexed and you can access them by referring to the index number:
Note: The first item has index 0.

Example:



Negative Indexing:

Negative indexing means start from the end

-1 refers to the last item, -2 refers to the second last item etc.

Example:



Range of Indexes:

You can specify a range of indexes by specifying where to start and where to end the range.

When specifying a range, the return value will be a new list with the specified items.

Example:

Return the third, fourth, and fifth item:

Note: The search will start at index 2 (included) and end at index 5 (not included).


By leaving out the start value, the range will start at the first item:

Example:
This example returns the items from the beginning to, but NOT including, "Carrot":




Range of Negative Indexes:

Specify negative indexes if you want to start the search from the end of the list:

Example:

This example returns the items from "orange" (-4) to, but NOT including "Coriander" (-1):



Check if Item exits:

To determine if a specified item is present in a list use the in keyword:

Example:


Change the Value in list:

To change the value of a specific item, refer to the index number.

Example:
Change the second item.


Append Items in list:

To add an item to the end of the list, use the append() method:

Example:
Using the append() method to append an item:


Insert Items in list:

To insert a list item at a specified index, use the insert() method.The insert() method inserts an item at the specified index:

Example:
Insert an item as the second position.


Remove specified Item in list:

The remove() method removes the specified item.

Example:
Remove (Banana)






Remove specified Item using POP in list:

The pop() method removes the specified index.

Example:



  • Python Tuples:
In Python, tuples are ordered collections of objects that, unlike lists, are immutable, meaning that their contents cannot be changed once created. Tuples are defined by items enclosed in parentheses (()), each item separated by a comma. 
Multiple data types such as integers, strings, and other tuples can be stored. Tuples are especially useful when you need to ensure data consistency throughout a program. Because tuples are immutable, they can be used as keys in dictionaries and elements in aggregates, where immutability is essential. Their stable nature makes tuples a reliable and efficient data structure for storing read-only data.

Tuples are used to store multiple objects in a single variable.
A tuple is one of the 4 built-in data types in Python for storing collected data, the other 3 being List, Set, and Dictionary, all with different types and functions.
A tuple is a structured and immutable collection of objects.
Tuples are encoded with round brackets.

Example:



Tuple Items:

In Python, a tuple is a collection of objects that can contain data types such as integers, strings, and even other tuples. Each object in a tuple is an element and is accessed by its index.

Ordered Tuple:

Tuples are ordered collections, which means that the objects have a defined order that won’t change. When you create a tuple, the order of the objects is stored.

Unchangeable Tuple:

Tuples are immutable, which means that once created, their contents cannot be changed. You cannot add, remove, or modify objects in a tuple.

Allow duplicates in  Tuple:

Tuples can contain duplicate elements. Each occurrence of an element is treated as a unique object based on its location in the tuple.

Example:

Tuple Length:

The length of a tuple specifies the number of elements. You can use the len() function to find the length of the tuple, which returns the total number of elements in the tuple.

Example:


Tuple Type:

The type() function can be used to check the type of the tuple, which returns <class 'tuple'>. This confirms that the object is indeed a tuple.

Example:


Create Tuple with one Item:

If you want to create a tuple with only one object, you must add a comma after the object, otherwise Python will not recognize it as a tuple.

Example:

Tuple Item - Data types:

Tuple items can be of any data type:

Example:
String, int and boolean data types:




Access Tuple Items:

Tuples are collections of structures, so you can access their properties via their index, which is similar to a list. Index 0 for the first item, 1 for the second item, and so on. Negative listing can also be used to get items from the end of tuples, where -1 means the last item, -2 means the second last item, and so on.

Example:
Print the second item in the tuple:


Negative Indexing  in Tuple :

Negative indexing between tuples can access elements at the end of the tuple. Index -1 indicates the last item, -2 indicates the second last item, and so on. This is useful when you want to access elements without knowing the exact length of the tuple.

Example:

Range of Indexes  in Tuple :

You can get a set of objects in a tuple by slicing. Slicing allows you to specify a start and end index, creating a new tuple of elements between these indices. The syntax for slicing is tuple [start:end], where start is the index of the first element included in the slice and end is the index of the first element removed from the slice.

Example:
Return the third, fourth and fifth item:



#This will return the items from position 2 to 5.

#Remember that the first item is position 0,
#and note that the item in position 5 is NOT included



Example:
This example returns the items from the beginning to, but NOT included, "spinach":


Example:
If the end value is omitted, the range will go to the end of the tuple:



Range of Negative Indexes  in Tuple :


When slicing is used, negative indices can be used to access a set of objects at the end of a tuple. This can be especially useful when you want to extract elements relative to the end of the tuple without knowing the exact length of the tuple.

Example:
This example returns the items from index -4 (included) to index -1 (excluded)


Add Items  in Tuple :

Tuples are immutable, that is, you cannot add, remove, or modify objects directly after the tuple is created. However, you can create a new tuple by adding the first tuple to another tuple containing the new objects. Alternatively, you can convert the tuple to a list, convert the list, and then convert it back to the tuple.

Add tuple to a tuple: 
You are allowed to add tuples to tuples, so if you want to add one item, (or many), create a new tuple with the item(s), and add it to the existing tuple:
Example:



  • Python Dictionaries :
A Python dictionary is a built-in data type that allows you to store and manage data as key-value pairs. A dictionary is an unordered collection of objects, meaning that it does not preserve any particular order for their objects. Each key in the dictionary must be unique and immutable, such as strings, numbers, or tuples, while the values ​​associated with a key can be any data type and can be duplicated.

Dictionaries are defined in Python by curly braces {} where each key-value pair is separated by a colon: and the two are separated by a comma.

Example:

Dictionary Items :

Dictionary objects in Python are key-value pairs, where each key is unique and maps to a value. Here is a simple example of dictionary objects:

Dictionary items are ordered, changeable, and do not allow duplicates.

Example:


Python Dictionary Overview :

Ordered or Unordered Dictionary  :

To say that a Dictionary is organized implies that there is a defined order of things, and that order will not change.

Unordered means that there is no order in the objects defined, and you cannot index the object.

Changeable (Mutable)? Dictionary  :

Yes, dictionaries are changing. Once the dictionary is created, you can add, change, or remove features.

Duplicates Not Allowed in Dictionary  :

Keys: Duplicate keys are not allowed. Each key must be unique in the dictionary. If you try to assign a new value to an existing key, the old value will be overridden.
Exception: Duplicate values ​​are allowed. The same value can be associated with different keys.

Example:


Dictionary Length  :

You can use the len() function to specify the length of the dictionary (i.e. the number of key-value pairs it contains).

Example:



Dictionary Items - Data Types  :

Key: A key can be any static data, such as strings, numbers, or tuples.
Value: A value can be any data type, including lists, tuples, other dictionaries, and so on.

Example:


In Python you can key into a dictionary. There are many ways to access and use dictionary resources.

Access dictionary Items :

You can access the items of a dictionary by referring to its key name, inside square brackets:

Example:


Using the  'get' Method     :

The 'Get' method is another way to get values. This is useful because not having a key does not cause an error, instead returning None (or the specified default value).

Example:


Accessing all keys    :

You can use the 'key' path to get all the keys in the dictionary.

Example:


Accessing all values  :

You can access all concepts in the dictionary using the 'values' ​​method.

Example:


Accessing all Items
  :

You can access all key-value pairs in a dictionary using the 'items' method:

Example:

Change Values in Dictionary  :

You can change the price of a particular product by checking its main name.

Example:

Update Dictionary  :

The update() method will update the dictionary with the contents of the given argument.

The argument must be a dictionary, or a repeatable object containing key:value pairs.

Example:


Add Items in Dictionary  :

Adding an item to the dictionary is done by using a new index key and assigning it a value:

Example:

Remove Items in Dictionary  :

Python has many ways to extract objects from a dictionary depending on your needs.

1. pop() method:

The pop() method removes the item with the specified key name:

Example:

2.  popitem() method:

The popitem() method removes the last embedded element (in versions prior to 3.7, random elements are removed instead).

Example:


3.  del keyword:

The del keyword extracts an object with the specified key name.
Example:


  • Python Sets :
A set in Python is an unordered collection of unique objects. Sets are used when an item in a collection is more important than its order or frequency of appearance. It is written in {} curly brackets.

Sets are used to store multiple items in a single variable.

A set is a collection of which is unordered means sets do not record element position or order of insertion, unchangeable , and unindexed means sets are unordered they do not support indexing or slicing operation.

Sets are unchangeable, but you can add new  and also remove items .

Example:

Duplicates in Set  :

By definition, sets cannot contain duplicate elements. When a set is created, or elements are added to the set, any duplicate values ​​are immediately removed, ensuring that each element in the set is unique.

Example:


Get the length of a Set  :

To get the length of a set in Python, which is the number of unique elements contained in the set, you can use the built-in len() function. The len() function returns the number of items (elements) in the set.

The len() function in Python, when applied to a set, returns the total number of unique elements in the set.

Example:


Set Items - Data types  :

In Python, a Set is an unordered collection of unique objects. Elements in a Set can contain different types of data. 

Below are descriptions of the types of data that can be added to a Set:
Set items can be of any data type, either String, int or boolean data type.

Example:

String, int and boolean data types:




Example 2:

Type of a set :



Access Set items:

Sets in Python are unordered collections of unique objects. This means that no index can access elements directly as in lists or tuples. However, you can access the contents of a set by using loops or converting the set to a list or tuple.

Example:


Checking for Specific Item: 





Add items in set:

Sets in Python are mutable, which means you can add items after they have been created. There are several ways to add items to a set: add(), update(), and using the union operator.

Example:

Update Set Items:

Use the update() method to add items from another set to the current set.

Example:
Add elements from yourset into myset:



Remove Set Items:

In Python, you can remove items from a set using various methods.
 Each method has its own behaviors, especially when dealing with items that may or may not be in the set.

1.remove() Method:

The remove() method removes the specified item from the set. It raises a KeyError if the object is not found.

Example:



2.discard() Method:

The discard() method also removes the specified items from the set, but unlike remove(), 
it does not raise an error if the object is not found.

Example:




Post a Comment

0 Comments