0% found this document useful (0 votes)
5 views9 pages

Understanding Python Data Types

The document provides an overview of Python data types, categorizing them into Numeric, Sequence, Mapping, Boolean, Set, and Binary types. It explains the characteristics and usage of each type, including examples of integers, floats, strings, lists, tuples, dictionaries, and sets. Additionally, it covers how to create, access, and manipulate these data types in Python programming.

Uploaded by

Bala Somesh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Understanding Python Data Types

The document provides an overview of Python data types, categorizing them into Numeric, Sequence, Mapping, Boolean, Set, and Binary types. It explains the characteristics and usage of each type, including examples of integers, floats, strings, lists, tuples, dictionaries, and sets. Additionally, it covers how to create, access, and manipulate these data types in Python programming.

Uploaded by

Bala Somesh
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Data types are the classification or categorization of data items.

It represents the kind of


value that tells what operations can be performed on a particular data. Since everything is an object
in Python programming, Python data types are classes and variables are instances (objects) of these
classes. The following are the standard or built-in data types in Python:

• Numeric - int, float, complex

• Sequence Type - string, list, tuple

• Mapping Type - dict

• Boolean - bool

• Set Type - set, frozenset

• Binary Types - bytes, bytearray, memoryview

DataTypes

This code assigns variable 'x' different values of few Python data types - int, float, list, tuple and
string. Each assignment replaces the previous value, making 'x' take on the data type and value of
the most recent assignment.

# int, float, string, list and set

x = 50

x = 60.5

x = "Hello World"

x = ["geeks", "for", "geeks"]

x = ("geeks", "for", "geeks")


1. Numeric Data Types in Python

The numeric data type in Python represents the data that has a numeric value. A numeric value can
be an integer, a floating number, or even a complex number. These values are defined as Python
int, Python float and Python complex classes in Python.

• Integers - This value is represented by int class. It contains positive or negative whole
numbers (without fractions or decimals). In Python, there is no limit to how long an integer
value can be.

• Float - This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by
a positive or negative integer may be appended to specify scientific notation.

• Complex Numbers - A complex number is represented by a complex class. It is specified


as (real part) + (imaginary part)j . For example - 2+3j

a=5

print(type(a))

b = 5.0

print(type(b))

c = 2 + 4j

print(type(c))

Output

<class 'int'>

<class 'float'>

<class 'complex'>

2. Sequence Data Types in Python

The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence data types of Python:

• Python String

• Python List

• Python Tuple

String Data Type

Python Strings are arrays of bytes representing Unicode characters. In Python, there is no character
data type Python, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes or even triple quotes. We can
access individual characters of a String using index.

s = 'Welcome to the Geeks World'

print(s)

# check data type

print(type(s))

# access string with index

print(s[1])

print(s[2])

print(s[-1])

Output
Welcome to the Geeks World

<class 'str'>

List Data Type

Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.

Creating a List in Python

Lists in Python can be created by just placing the sequence inside the square brackets[].

# Empty list

a = []

# list with int values

a = [1, 2, 3]

print(a)

# list with mixed int and string


b = ["Geeks", "For", "Geeks", 4, 5]

print(b)

Output

[1, 2, 3]

['Geeks', 'For', 'Geeks', 4, 5]

Access List Items

In order to access the list items refer to the index number. In Python, negative sequence indexes
represent positions from the end of the array. Instead of having to compute the offset as in
List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end, -1
refers to the last item, -2 refers to the second-last item, etc.

a = ["Geeks", "For", "Geeks"]

print("Accessing element from the list")

print(a[0])

print(a[2])

print("Accessing element using negative indexing")

print(a[-1])

print(a[-3])

Output

Accessing element from the list

Geeks

Geeks

Accessing element using negative indexing

Geeks

Geeks

Tuple Data Type

Just like a list, a tuple is also an ordered collection of Python objects. The only difference between a
tuple and a list is that tuples are immutable. Tuples cannot be modified after it is created.

Creating a Tuple in Python

In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’
with or without the use of parentheses for grouping the data sequence. Tuples can contain any
number of elements and of any datatype (like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.

# initiate empty tuple

tup1 = ()

tup2 = ('Geeks', 'For')

print("\nTuple with the use of String: ", tup2)

Output

Tuple with the use of String: ('Geeks', 'For')

Note - The creation of a Python tuple without the use of parentheses is known as Tuple Packing.

Access Tuple Items

In order to access the tuple items refer to the index number. Use the index operator [ ] to access an
item in a tuple.

tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items

print(tup1[0])

print(tup1[-1])

print(tup1[-3])

Output

3. Boolean Data Type in Python

Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by the class
bool.

Example: The first two lines will print the type of the boolean values True and False, which is <class
'bool'>. The third line will cause an error, because true is not a valid keyword in Python. Python is
case-sensitive, which means it distinguishes between uppercase and lowercase letters.

print(type(True))
print(type(False))

print(type(true))

Output:

<class 'bool'>
<class 'bool'>

Traceback (most recent call last):


File "/home/[Link]", line 8, in
print(type(true))
NameError: name 'true' is not defined

4. Set Data Type in Python

In Python Data Types, Set is an unordered collection of data types that is iterable, mutable, and has
no duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.

Create a Set in Python

Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need
not be the same, various mixed-up data type values can also be passed to the set.

Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values

# initializing empty set

s1 = set()

s1 = set("GeeksForGeeks")

print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])

print("Set with the use of List: ", s2)

Output

Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}

Set with the use of List: {'Geeks', 'For'}

Access Set Items

Set items cannot be accessed by referring to an index, since sets are unordered the items have no
index. But we can loop through the set items using a for loop, or ask if a specified value is present in
a set, by using the in the keyword.
set1 = set(["Geeks", "For", "Geeks"])

print(set1)

# loop through set

for i in set1:

print(i, end=" ")

# check if item exist in set

print("Geeks" in set1)

Output

{'Geeks', 'For'}

Geeks For True

5. Dictionary Data Type

A dictionary in Python is a collection of data values, used to store data values like a map, unlike other
Python Data Types that hold only a single value as an element, a Dictionary holds a key: value pair.
Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary
is separated by a colon : , whereas each key is separated by a ‘comma’.

Create a Dictionary in Python

Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated
and must be immutable. The dictionary can also be created by the built-in function dict().

Note - Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.

# initialize empty dictionary

d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

print(d)

# creating dictionary using dict() constructor

d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})

print(d1)
Output

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Accessing Key-value in Dictionary

In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. Using get() method we can access the dictionary elements.

d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key

print(d['name'])

# Accessing a element using get

print([Link](3))

Output

For

Geeks

Python Data Type Exercise Questions

Below are two exercise questions on Python Data Types. We have covered list operation and tuple
operation in these exercise questions. For more exercises on Python data types visit the page
mentioned below.

Q1. Code to implement basic list operations

fruits = ["apple", "banana", "orange"]

print(fruits)

[Link]("grape")

print(fruits)

[Link]("orange")

print(fruits)

Output

['apple', 'banana', 'orange']

['apple', 'banana', 'orange', 'grape']


['apple', 'banana', 'grape']

Q2. Code to implement basic tuple operation

coordinates = (3, 5)

print(coordinates)

print("X-coordinate:", coordinates[0])

print("Y-coordinate:", coordinates[1])

Output

(3, 5)

X-coordinate: 3

Y-coordinate: 5

Common questions

Powered by AI

Python's set data types are characterized by their unordered nature, mutability, and the uniqueness of elements they contain . This is in contrast to lists, which are ordered and can contain duplicate elements, making them suitable for ordered collections of data where duplicates are allowed . Meanwhile, dictionaries provide key-value pair storage, facilitating fast lookups and retrievals by keys . Sets are typically used when the primary concern is membership testing and existence, allowing operations like unions and intersections to be performed efficiently . These properties make sets particularly useful for tasks involving deduplication, value tracking, and rapid element search within unordered collections .

Python's sequence data types, such as strings, lists, and tuples, enable efficient data organization and manipulation by offering a variety of methods to access, modify, and process data . Strings allow for easy character access and manipulation via indexing and slicing, crucial for text processing tasks . Lists provide mutable sequences, allowing for dynamic data storage and modification such as appending, concatenating, or sorting, which is ideal for tasks requiring flexible item management . Tuples, being immutable, are optimally used in situations where data integrity is crucial and fixed data is preferred, reducing overhead and potentially enhancing performance through optimization by Python's internal mechanisms . Collectively, these sequence types support iterative and indexing operations, thereby simplifying various programming tasks like data analysis, processing collections of items, and maintaining ordered workflows .

In Python, everything is represented as an object, which means data types are essentially classes, and variables are instances of these classes . This concept allows Python to treat each data type uniformly, providing a consistent interface and behavior across different types. Consequently, when a variable is instantiated, it is essentially creating an instance of a class, which inherently includes methods and properties defined by that class . This object-oriented approach facilitates polymorphism and encapsulation, enabling variables of different types to be used interchangeably in many contexts, enriching Python's flexibility and versatility as a programming language .

Lists in Python are mutable data structures, which means their contents can be changed (elements can be added, removed, or altered). In contrast, tuples are immutable, meaning once they are created, their elements cannot be altered, removed, or added . This fundamental difference also has performance implications, as tuples can be more memory-efficient than lists due to their immutability, which allows Python to optimize their storage and access .

Sequence indexing in Python significantly enhances data manipulation capabilities by allowing for direct access to elements within sequences through positive and negative indices . Negative indexing, which starts from the end of the sequence, provides a flexible mechanism to directly access elements without recalculating offsets, a common necessity in backward traversals or reverse operations . This capability allows programmers to easily manipulate data sets, perform reverse iterations, and enhance the readability and conciseness of the code when dealing with sequence data types like lists, strings, and tuples . Such indexing practices are particularly powerful in scenarios requiring data slicing, reversing sequences, or removing elements from the end, offering enhanced flexibility and operational efficiency in programming .

In Python, the boolean data type is integrated into its dynamic typing system, allowing any object to be evaluated in a boolean context . This makes Python's logical operations versatile, as non-boolean values can be tested for truthiness or falsiness, supporting implicit type conversions common in conditional statements . For example, in Python, zero values, empty collections, or None are treated as False, while non-zero numbers, non-empty collections, and objects are seen as True . This dynamic typing and context-sensitive evaluation facilitate streamlined code expressions and conditionals but require careful consideration to prevent unintended logical errors, especially when managing various data types in complex logical evaluations .

Using complex numbers in Python offers several benefits, particularly for scientific computations involving complex mathematical models. Python's native support for complex numbers via the complex class allows for direct representation and computation with complex arithmetic, facilitating tasks in fields like engineering, physics, and applied mathematics where such calculations are common . However, challenges may arise due to the lack of precision inherent in floating-point arithmetic that underlies complex numbers, leading to potential rounding errors and inaccuracies in computations . Despite this, Python's robust libraries (like NumPy and SciPy) complement complex number operations by providing extensive functions and capabilities to mitigate precision issues and enhance computational efficacy in scientific environments .

Python dictionaries enhance data retrieval and storage efficiency through their use of hash tables to store key-value pairs, allowing for constant average time complexity (O(1)) for lookups, insertions, and deletions . Unlike lists and tuples, where accessing elements involves indexing or searching sequentially, dictionary operations are faster and more efficient for large datasets due to this hashing mechanism . This makes dictionaries particularly suited for applications where rapid access and manipulation of data via unique keys are essential, such as data indexing, real-time applications, and constructing associative arrays . Additionally, dictionary keys, which are immutable, provide a robust way to map heterogeneous data types, creating flexible and extensive data storage mechanisms that surpass fixed-size and order constraints of sequence types .

Python's numeric data types, which include int, float, and complex, each serve unique functions in terms of mathematical precision. The int type can handle arbitrarily large numbers within the limits of the machine's memory, avoiding overflow errors common in many other languages . However, float, which represents real numbers, is subject to rounding errors due to its finite precision under IEEE 754 standards, which can affect computations that demand high precision . Complex numbers in Python allow for the direct representation of complex mathematical computations but do not mitigate floating-point inaccuracies inherent in calculations involving real and imaginary parts .

Memoryview objects in Python provide a means of accessing the internal data of objects that support the buffer protocol without copying the object data . This feature can have significant advantages in memory-intensive applications or when processing large datasets, as it allows for efficient data handling by avoiding duplicate memory allocations. For example, when working with large binary data buffers, using memoryviews can reduce memory footprint and increase processing speed by enabling direct access to the data stored in memory . This functionality is particularly beneficial in applications that require high-performance data analysis, such as real-time data streaming, scientific computing, or graphics processing, where the overhead of data copying can be prohibitive .

You might also like