An ndarray is a data structure provided by Python’s NumPy library. While an ndarray may look similar to list at first glance, it differs in its properties at various points. Unlike list, an ndarray has a fixed length and a homogenous data type holding ability.
Data Types in Python
Data types in Python define the kind of data a variable can hold and determine how that data can be manipulated, ensuring efficient and accurate data handling.
To stay organized, we've developed various methods for managing different types of data in our daily lives. For instance, we often use sticky notes on the refrigerator door to remind ourselves of daily tasks. However, carrying a board full of sticky notes around while shopping might not be the best choice. Instead, a shopping checklist is a much better solution.
In the same way, when coding, we encounter different types of data. Python uses labels, known as data types, to identify and handle the kind of data it’s dealing with. Sometimes, we specify the data type by using specific syntax when storing a value. Other times, we can instruct Python to interpret certain data in a particular way using built-in functions.
Data types supported by Python
Python offers a variety of data types, each designed to cater to specific needs. These data types can be categorized as follows:
Numeric data types
Integers
Floating-point numbers
Complex numbers
Collection data types
Sequential collections
Strings (text)
Lists
Tuples
Unordered collections
Sets
Dictionaries
Boolean data
Let's dive into these types, exploring what they store, why they're useful, and how to use them.
Numeric data types
Numeric data types are used to store numbers. They can be of three types, integers, floating-point numbers, or complex numbers.
Integers
The integer data type is used for whole numbers, like 5, -12, or 0. Integers are used when you need to count things as the number of items in a list or the iteration count in a loop.
age = 25 # An integer representing ageprint("Age: ", age)
Floating-point values
Floating-point values represent real numbers, including those with a decimal point, such as 3.14 or -0.001. They are useful for calculations requiring more precision than integers.
pi = 3.14159 # A floating-point number representing Piprint("The values of pi:", pi)
Complex numbers
Complex numbers have a real and an imaginary part, are are used in advanced mathematical computations. Python makes it easy to work with these numbers using the j suffix for the imaginary part.
complex_num = 2 + 3j # A complex number with real part 2 and imaginary part 3print(complex_num)print(complex_num.real)print(complex_num.imag)
Collection data types
Collection data types in Python allow you to store multiple items in a single variable. They are divided into sequential and unordered types.
Sequential data types
In sequential data types, the order of elements is fixed. Whenever we access the elements, we will find them right where they were when defined. Elements in sequential data types can be accessed using index values starting from 0 for the first element, 1 for the second and so on.
String (text)
A string is a sequence of characters joined together. The string data type in Python is used to store the simple text of arbitrary sizes. To define a string, we enclose the text we want within single, double, or triple quotes.
greeting = 'Hello, World!' # A string declared using single quoteswelcome = "Welcome to Educative." # A string declared using double quotesintro = '''A great place to learn how to code.''' # A string declared using triple quotesprint(greeting, welcome, intro)
Try experimenting with the codes!
Play around and see how it changes the expected outputs.
List
A list is an ordered collection that can hold items together. Lists are defined by enclosing comma-separated elements within square brackets. Elements can be added or removed from a list using .append() or .remove() functions.
fruits = ["apple", "banana", "cherry"] # A list of fruit names saved as stringsprint("Original list:", fruits)fruits.remove("banana") # Removing an elementprint("After removing an element:", fruits)fruits.append(10) # Adding an element of an integer typeprint("After adding an integer:", fruits)print("Accessing the second element from the list:", fruits[1])
Tuple
However, tuples are immutable, meaning that once created, their elements can be accessed through indexing but cannot be modified. To define tuples, we enclose comma-separated elements within round brackets.
dimensions = (1920, 1080) # A tuple representing screen dimensionsprint("Accessing the first element from the list:", dimensions[0]) # Access the first element
Unordered data types
Unordered data types do not maintain the order of elements. Whenever we access the elements, there is no guarantee that we will find them in the order that we saw when we accessed them at an earlier stage.
Set
A set is an unordered collection of unique elements. Sets are useful for storing data where duplication isn't allowed and for performing set operations like union and intersection. To define a set, we enclose elements within curly brackets.
unique_numbers = {1, 2, 3, 4, 5, 5} # Duplicate '5' will be ignoredprint(unique_numbers)unique_numbers.add(6) # Adding an elementprint(unique_numbers)
Dictionary
A dictionary is a collection of key-value pairs where each key maps to a value. Data in dictionaries can be efficiently and conveniently looked up by using keys instead of index values. A dictionary is defined by enclosing comma-separated key:value pairs within curly brackets, and a list of all available keys can be obtained using the keys() method.
student = {"name": "Alice", "age": 21, "grade": "A"} # A dictionary representing a studentprint(student["name"]) # Access value using key, Output: 'Alice'student["age"] = 22 # Modify the valueprint(student.keys()) # Output: dict_keys(['name', 'age', 'grade'])
Boolean data type
The Boolean data type represents one of two values: True or False. Booleans are often used in conditions and comparisons.
condition = False # Defining a condition# If the value stored in the "condition" variable is "True", this block will execute.if condition is True:print("The condition is true.")# If the value stored in the "condition" variable is "False", this block will execute.elif condition is False:print("The condition is false.")
You can toggle between which conditional block of code gets executed by changing the boolean value stored in the condition variable. Consider changing it to True and then run the program.
Go ahead and give it a try!
Checking data type
So far, we have seen how we can use specific syntax to ensure that Python is able to identify the data type we want the variable to have. However, we cannot possibly remember and keep track of the data type of every variable we have in a program, can we? For this purpose, Python has a built-in function—type()—that lets us check the data type of any item in Python.
The code below might be too long for a single code window. Scroll in the window below to see the rest of the code.
# Numeric Data Typesint_var = 42float_var = 3.14complex_var = 1 + 2j# Collection Data Types# Sequentialstr_var = "Hello, Python!"list_var = [1, 2, 3, "apple", 5.6]tuple_var = (True, False, "Tuple", 3.5)# Unorderedset_var = {1, 2, 3, "banana"}dict_var = {"name": "Alice", "age": 30, "is_student": False}# Boolean Data Typebool_var = True# Using type() to check the data type of each variableprint(f'Type of int_var: {type(int_var)}')print(f'Type of float_var: {type(float_var)}')print(f'Type of complex_var: {type(complex_var)}')print(f'Type of str_var: {type(str_var)}')print(f'Type of list_var: {type(list_var)}')print(f'Type of tuple_var: {type(tuple_var)}')print(f'Type of set_var: {type(set_var)}')print(f'Type of dict_var: {type(dict_var)}')print(f'Type of bool_var: {type(bool_var)}')
Key takeaways
Python's built-in data types: Python supports a wide range of data types, each having its special characteristics:
Integers and floats: Handle numerical data, with integers representing whole numbers and floats representing decimal values.
Strings: Store sequences of characters and support indexing and slicing.
Lists and tuples: Allow for storing multiple elements, with lists being mutable and tuples immutable.
Sets: Store unique elements.
Dictionaries: Hold key-value pairs, making them ideal for lookups.
Booleans: Used to represent
TrueorFalse, often in control flow operations.
Mutability matters: Understanding the difference between mutable (e.g., lists, dictionaries) and immutable (e.g., strings, tuples) data types is essential, as it affects how data can be modified after it’s created.
Data type checking with
type(): Python allows you to check the type of a variable using thetype()function, which can be useful for debugging and ensuring correct data handling.
Choosing the right data type for the task improves the efficiency, readability, and functionality of your code, making it a fundamental skill for any Python programmer.
Become a Python developer with our comprehensive learning path!
Ready to kickstart your career as a Python Developer? Our Become a Python Developer path is designed to take you from your first line of code to landing your first job.
This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
What is an ndarray?
How to define a matrix in Python?
How can I learn to code?
Free Resources