Data Types in Python with Examples

Sakshi Dhameja  20 min read
27 Sep 2023
Beginner
2.21K Views

Data Types in Python: An Overview

If you’re coding in the Python programming language, it can quickly become overwhelming with all of the data types available. It is incredibly important to understand these data structures, as they make coding more efficient and help ensure that your programs run correctly. With so many options, it can be daunting to figure out which type best suits a given situation. In this blog post, we’ll explore the Data types in Python, Data types in Python with example, Python Data Types explaining what each one is used for and how they compare to one another. Whether you're new to coding or an experienced programmer looking for Python training, this article has something for everyone!

What is a Data Type in Python?

A data type in Python is a classification of data that determines which characteristics and capabilities are associated with it. It can be used to identify data ranging from string variables, numerical data, lists, tuples, and dictionaries. Knowing the data type enables the interpreter to allocate memory for any data element and then allow relevant operations applicable to that data type. These data types are an essential part of the Python programming language since they provide the framework that all programs follow. A clear understanding of these data types gives the user more control when writing the programs, allowing them to choose the right data type for each data element according to the program requirements and expectations.

Types of Data Types in Python

Python has various built-in data types which will be discussed in this article:

  • Numeric - int, float, complex
  • String - str
  • Sequence - list, tuple, range
  • Binary - bytes, bytearray, memoryview
  • Mapping - dict
  • Boolean - bool
  • Set - set, frozenset
  • None - NoneType

Numeric data types in Python

Python is a powerful programming language that offers numeric data types in Python as a convenient way for programmers to structure numeric data. By taking advantage of numeric data types, Python enables programmers to produce efficient code while managing numeric data more effectively than ever before. Python programming language supports four different numerical types −
  • int (signed integers)
  • long (long integers, they can also be represented by octal and hexadecimal)
  • float (floating point real values)
  • complex (complex numbers)
Here are some examples of different types of numbers-

intlongfloatcomplex
1051924361L0.03.14j
100-0x19323L15.2045.j
-7860122L-21.99.322e-36j
0800xDEFABCECBDAECBFBAEl32.3+e18.876j
-0490535633629843L-90.-.6545+0J
-0x260-052318172735L-32.54e1003e+26J
0x69-4721885298529L70.2-E124.53e-7j

Example

# integer variable.
a=150
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.846
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=18+3j
print("The type of variable having value", c, " is ", type(c))

In this code, three variables (a, b, and c) are defined with three different data types (integer, float, and complex), and each variable's type and value are printed.

Output

The type of variable having value 150 is <class 'int'>
The type of variable having value 20.846 is <class 'float'>
The type of variable having value (18+3j) is <class 'complex'>

Python String Data Type

  • The string data type in Python is very useful and versatile.
  • It allows the developer to process string values that contain both alphanumeric characters and symbols.
  • Working with string data types can be done using various string methods within the Python programming language, giving the user the freedom to manipulate string data sets in a variety of ways.
  • Additionally, string literals can also be used within a string variable, allowing for even more efficient manipulation of string data by allowing predefined sets of variables and specialized syntax under the same variable name.
  • Subsets of strings of the Python language can be taken by using the slice operator ([ ] and [:] ) with all the indexes that start at 0 at the beginning of the string and then work their way from -1 at the end.

Example

str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string stating from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string

With the help of this code, you can see how to do a number of string operations in Python, such as printing the complete string, accessing particular characters, slicing the string to get a substring, repeating the text, and concatenating it with another string.

Output

Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST

Python List Data Type

  • Python list data type is an essential tool for programming.
  • It holds multiple values in an organized and efficient way, allowing programmers to edit, store, and access complex sets of data with a single instruction.
  • It is one of the most versatile data structures that Python has to offer, as the list can store anything from strings to complex objects.
  • Python list data type is a very important feature for high-level programming applications because it allows the user to keep track of multiple pieces of information at once.
  • The values that are stored in a Python list can be accessed by using the slice operator ([ ] and [:]) with indexes starting at 0 at the beginning of the list and working their way to end -1.
  • The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

Example

list = [ 'abcd', 786 , 2.23, ‘Scholar-Hat’, 70.2 ]
tinylist = [123, 'Scholar-Hat']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd 
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists

Working with Python lists is shown by this code. It introduces two lists, "list" and "tinylist," and it illustrates a number of list actions, such as printing the complete list, accessing specific components, slicing to extract a sublist, repeating a list, and concatenating two lists.

Output

['abcd', 786, 2.23, 'Scholar-Hat', 70.2]
abcd
[786, 2.23]
[2.23, ‘Scholar-Hat', 70.2]
[123, 'Scholar-Hat', 123, 'john']
['abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat']

Tuple data type in Python

  • Tuple data type in Python is a powerful and flexible type of data structure.
  • Tuple objects are sequences of immutable Python objects that can hold a group of elements together.
  • Tuple data type is incredibly versatile since its elements can be of any data type, including numbers, strings, lists, dictionaries, and even other tuples.
  • Tuple operation is simpler than those for lists since they cannot be altered multiple times.The 
  • Tuple data type is different from the list data type in Python because List data types are enclosed in brackets ( [ ] ) and their elements and size can be changed, but the tuple data types are enclosed in parentheses ( ( ) ) and cannot be updated.

Example

tuple = ( 'abcd', 786 , 2.23, 'Scholar-Hat', 70.2 )
tinytuple = (123, 'Scholar-Hat')
print (tuple) # Prints the complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd 
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
print (tuple + tinytuple) # Prints concatenated tuples

Python tuples are used in this code to show how they work. It introduces two tuples, "tuple" and "tinytuple," defines them, and illustrates a number of tuple operations, such as publishing the complete tuple, accessing each member, slicing to extract a sub-tuple, repeating a tuple, and concatenating two tuples.

Output

('abcd', 786, 2.23, 'Scholar-Hat', 70.2)
abcd
(786, 2.23)
(2.23, 'Scholar-Hat', 70.2)
(123, ‘Scholar-Hat', 123, 'Scholar-Hat')
('abcd', 786, 2.23, 'Scholar-Hat', 70.2, 123, 'Scholar-Hat')

Range data type in Python

Range data type in Python is an in-built feature of the Python programming language. It returns a sequence of numbers that starts from 0 and increments to 1 until it reaches a specified number. The developer uses the range() function with various loops, such as for and while loop for generating a sequence of numbers.

The description of the parameters used in Python language:

    • start: In this parameter, it uses an integer number to specify the starting position, (It is optional, Default: 0)
    • stop: In this parameter, it uses an integer number to specify the starting position (It's mandatory)
    • step: In this parameter, it uses an integer number to specify increment, (Its optional, Default: 1)

    Example

    for i in range(1, 5):
      print(i)

    This program iterates over numbers from 1 to 4 (inclusive) and writes each one on a separate line using a for loop.

    Output

    1
    2
    3
    4
    

    Dictionary data type in Python

    • Python’s Dictionary data type is a powerful and versatile tool that allows users to quickly store, access, and manipulate data.
    • By using a key-value pair model, Dictionary data types in Python enable coders to easily remember and store information without the need for complicated variable names.
    • Dictionary data types are also simple to use as Python automates most of the mundane setup tasks involved in creating Dictionary objects.
    • Dictionaries in Python language are enclosed by curly braces ({ }) and their values can be assigned and accessed using square braces ([]).

    Example

    dict = {}
    dict['one'] = "This is one"
    dict[2] = "This is two"
    tinydict = {'name': 'Scholar-Hat','code':6734, 'dept': 'sales'}
    print (dict['one']) # Prints value for 'one' key
    print (dict[2]) # Prints value for 2 key
    print (tinydict) # Prints complete dictionary
    print (tinydict.keys()) # Prints all the keys
    print (tinydict.values()) # Prints all the values

    The use of dictionaries in Python is shown by the following code. It performs several activities, such as accessing values by keys, printing the complete dictionary, and showing keys and values individually for 'tinydict', and defines three dictionaries: 'dict', and 'tinydict'.

    Output

    This is one
    This is two
    {'dept': 'sales', 'code': 6734, 'name': 'Scholar-Hat'}
    ['dept', 'code', 'name']
    ['sales', 6734, 'Scholar-Hat']
    

    Boolean data type in Python

    • Boolean data type in Python is a powerful way to store and assign boolean (true or false) values in that particular code.
    • It can be used to control program flow, perform boolean operations, and assign boolean variables.
    • Boolean data types provide easy-to-understand answers, usually, the answer is either true or false; 0 or 1 if it’s stored as an integer.
    • In the Python programming language boolean data type is one of the built-in data types which represents one of the two values either True or False.
    • Python bool() function allows the developer to evaluate the value of any expression and returns either True or False based on the expression.

    Example

    a = True
    # display the value of a
    print(a)
    
    # display the data type of a
    print(type(a))

    The variable 'a' is given the Boolean value "True" by the following code, which then prints both the value ("True") and the data type ("bool") of the variable.

    Output

    true
    <class 'bool'>
    

    What is the data type conversion function?

    When manipulating data in Python, data type conversion is a necessity. However, data type conversion in Python is not always an easy task. In Python, there are many different data types including strings, integers, floats, and boolean. To successfully convert data from one data type to another, the user must use the proper data type conversion techniques built-in in Python. By using the built-in functions and methods available in Python, the user as well as the developer can convert data from one data type to another quickly and effectively.

    Example

    a = str(1) # a will be "1" 
    b = str(2.2) # b will be "2.2"
    c = str("3.3") # c will be "3.3"
    print (a)
    print (b)
    print (c)

    In this code, the numbers 1 and 2.2 are converted to string representations and assigned to variables 'a' and 'b', respectively. The string "3.3" is already present in variable "c". Following that, it prints the values of "a," "b," and "c," producing the output.

    Output

    1
    2.2
    3.3

    How to check Data Type in Python?

    These steps can be used to determine the data type of a variable or value in Python:

    • Give a variable a value or choose the value whose data type you want to examine.
    • To ascertain the variable's or value's data type, use the type() function.
    • To see the data type, print the outcome.

    FAQs

    1. How can I perform mathematical operations with numeric data types?

    For mathematical operations in Python with numeric data types, use operators like +, -, *, and /.

    2. When should I use complex numbers in Python?

    When calculating with both real and fictional components, use complex numbers.

    3. How can I manipulate and format strings?

    Use tools like str.format() or f-strings to manipulate and format strings.

    4. What are some common string operations?

    Slicing, concatenating, and searching with tools like find() and split() are common string operations.

    5. How can I add or remove elements from a Python list?

    Lists can be modified by adding with append() or extend(), removing with remove() or pop(), or using list comprehensions.

    6. How can I check if an element exists in a Python List?

    Use the "in" keyword or the index() method on lists to verify an element's presence.

    7. What are sequence types in Python?

    Lists, tuples, and strings are examples of sequence types.

    8. How do lists and tuples differ?

    Tuples are immutable (unchangeable), whereas lists are mutable (may be changed).

    9. When should I use the range data type?

    If you want to loop through a list of numbers, use the range data type.

    10. How can I convert a Python Range into a list or other iterable?

    Use list(range()) to turn a Python Range into a list or a for loop to iterate directly.

    11. How many data types are there in Python?

    There are numerous data types available in Python, including int, float, str, bool, list, tuple, dict, set, and others.

    12. What is the difference between mutable and immutable data types in Python, and why does it matter?

    Lists are an example of a mutable data type, while tuples are an example of an immutable type.

    13. What are the common pitfalls or issues related to data types in Python, and how can I avoid them?

    Random type conversions, changeable default parameters, and data loss during type conversions are common hazards. To prevent these problems, use explicit type handling.

    14. What is a data type in Python?

    The kind of data an object can contain, such as numbers, texts, or lists, is defined by its data type in Python.

    Summary

    Python has five standard data types − integers, floating point numbers, strings, lists, and dictionaries. In addition, Python also provides some special data types such as files, frozen sets, and a few more. Data structures are very important in programming. Different languages have different ways of representing data structures. Thus, knowing the difference between them is very essential while coding in any language. This was all about the basics of data types in Python, if you want to go deeper into data types then consider enrolling in a Python course. Stay tuned for our next blog where we will discuss advanced techniques and strategies for working with these data types!

    Share
    About Author
    Sakshi Dhameja (Author and Mentor)

    She is passionate about different technologies like Java, Python, C, C++ etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like JavaScript and Cloud.

    Accept cookies & close this