What Are Data Types in Python With Examples? | Airbyte (2024)

The foundation of any Python program is understanding how data is stored, represented, and manipulated. Here, we'll delve into Python data types, the essential building blocks defining the kind of information your variables can hold. From numbers to text and even collections of data, this article will explore the most common types with clear examples, giving you a strong grasp of how to structure your Python code effectively.

What are Python Data Types?

In Python, data types refer to classifying data objects based on their characteristics and operations. They define the types of values variables can hold and the kinds of operations you can perform on them. Python supports various popular data types like strings, numbers, and boolean. Let's have a deeper look at these data types with examples:

Python String Data Type

Strings in Python are fundamental data types used to represent sequences of characters. They are versatile and widely used for storing and manipulating textual data. You can create strings using either single quotes ('), double quotes ("), or triple quotes (''' or """).

Here is an example of a string in Python:

# Create strings using different quotesmessage1 = 'Hello, world!' # Single quotesmessage2 = "This is a string with double quotes."message3 = """This string spans multiple lines using triple quotes."""# Print on separate linesprint("Messages:", message1, message2, message3, sep="\n") # Access characters using indexfirst_letter = message1[0] # first_letter will be 'H'last_word = message2[-4:] # last_word will be "quotes." (slice up to, but not including, index -4)print("First letter:", first_letter)print("Last word:", last_word)# String Slicing and Concatenationgreeting = message1[:5] # greeting will be "Hello"place = "world" #place will be “world”full_message = greeting + ", " + place + "!"print("Full message:", full_message)# String methods - upper and lower caseuppercase_message = message1.upper() # uppercase_message will be "HELLO, WORLD!"lowercase_message = message2.lower()print("Uppercase:", uppercase_message)print("Lowercase:", lowercase_message)# Find and replacereplaced_message = message3.replace("string", "sentence") # Replace first occurrenceprint("Replaced string:", replaced_message)# Formatted string (f-string)name = "Bob"age = 25greeting_fstring = f"Hi, {name}. You are {age} years old."print(greeting_fstring)

Python Numerical Data Type

Numbers or Numeric data types in Python are used for representing numerical values and performing calculations. Here's a breakdown of the three main numeric data types:

  • Integers (int): Integers are the data types that represent the whole numbers (positive, negative, or zero). In Python, integers generally have unlimited precision, meaning they can store large or small whole numbers.

Example:age = 30population = 1234567

  • Floating-Point Numbers (float): Float represent real numbers with a decimal point. The range of float is approximately 3.4E-38 to 3.4E+38.

Example:pi = 3.14159 # Approximation of pigravity = 9.81 # Meters per second squared

  • Complex Numbers: Complex numbers show the values with real and imaginary parts. The imaginary value is denoted by a letter and real through a number.

Example:z = 3 + 2j # Real part is 3, imaginary part is 2

Python Boolean Data Type

The Boolean data type represents logical values, specifically True or False. It's fundamental for making decisions and controlling the flow of your program based on certain conditions.

Below is an example of a Boolean data type:

is_loggedIn = True # Assigning True to a variableage = 25is_adult = age >= 18 # Assigning True/False based on a comparisonif is_loggedIn: print("Welcome back!") # Code executes if is_loggedIn is Trueif is_adult: print("You are eligible to vote.")else: print("You are not yet eligible to vote.") # Code executes based on is_adult value

However, in addition to these data types, Python also supports mutable data types such as dictionaries, sets, and lists and immutable data types like tuples. The below section will give you a detailed description of these data types with examples.

Mutable Data Types

Mutable data types in Python are those whose data values can be modified after creation. You can add, change, or remove elements within the data structure. Mutable data types are further divided into three parts.

Dictionaries

A Python dictionary is a collection of elements. However, it stores the items in a key-value format. Here, the key is a unique identifier for its associated value, while the value can be any type of data you want to store in a dictionary. Two common ways to create a dictionary are by ‘{}’ separated by a comma or using a dict() function.

Here is an example showcasing various dictionary operations:

# Create a dictionary to store student informationstudent = { "name": "Alice", "age": 18, "course": "Computer Science", "grades": [85, 90, 78] # List as a value}# Accessing values using keysname = student["name"]age = student["age"]print(f"Student Name: {name}")print(f"Student Age: {age}")# Modifying a valuestudent["course"] = "Data Science" # Change course# Adding a new key-value pairstudent["scholarship"] = True# Iterating through key-value pairsfor key, value in student.items(): print(f"{key}: {value}")# Checking if a key existsif "age" in student: print("Age key exists in the dictionary")# Accessing a non-existent key (safer method)grade = student.get("grade", "Not Found") # Returns "Not Found" if key doesn't exist#Assuming grades is a listprint(f"Average Grade: {sum(student['grades']) / len(student['grades'])}")

Sets

Sets in Python are the unordered collection of unique data elements. You can modify the overall collection of elements in a set but cannot change the individual items stored in it. For instance, if you add a string ‘apple’ to a set, you cannot change it to ‘orange’ later within the set.

The example below demonstrates creation, modification, membership checking, and finding intersections with other sets.

# Create a set of fruitsfruits = {"apple", "banana", "cherry"}# Print the set (order may differ each time)print("Original fruits:", fruits)# Check if an element exists (membership checking)if "mango" in fruits: print("Mango is in the set")else: print("Mango is not in the set")# Add a new elementfruits.add("mango")print("Fruits after adding mango:", fruits)# Remove an elementfruits.remove("cherry")print("Fruits after removing cherry:", fruits)# Find the intersection with another set (common elements)vegetables = {"potato", "tomato", "carrot"}common_items = fruits.intersection(vegetables)print("Common items between fruits and vegetables:", common_items)

Lists

Lists in Python are suitable for storing collections of items in a specific order. You can access these elements based on their position (index) in the list. Lists are heterogeneous, as they can hold different data types (like strings, numbers, or even other lists) within the same list.

Here is an example of creation and modification in a list:

# Create a list of numbersnumbers = [1, 5, 8, 2]# Print the listprint("Original numbers:", numbers)# Access an element using indexsecond_number = numbers[1] # second_number will be 5print("Second element:", second_number)# Add an element to the endnumbers.append(10)print("Numbers after adding 10:", numbers)# Insert an element at a specific indexnumbers.insert(2, 3) # Insert 3 at index 2print("Numbers after inserting 3:", numbers)# Remove the first occurrence of an elementnumbers.remove(2)print("Numbers after removing first 2:", numbers)# Remove and get the last elementlast_item = numbers.pop()print("List after popping:", numbers)print("Popped item:", last_item) # last_item will be 10# Sort the list in ascending ordernumbers.sort()print("Numbers sorted in ascending order:", numbers)# Reverse the order of elementsnumbers.reverse()print("Numbers in reversed order:", numbers)

Immutable Data Types

Immutable data types are those whose elements cannot be changed once created. Any attempt to modify an immutable object will always create a new object.

For example, in Python, when you write X = 5, then it means, X = X + 1. You're not modifying the original value when you add a new value to the variable X. Instead, you create a new value and add it to the variable.

Tuples is a common immutable data type in Python.

Tuples

A tuple is an ordered collection of data items that cannot be changed after creation. It can be declared within parentheses with a comma in between. The example below demonstrates how you can work with tuples, considering their ordered and immutable nature.

# Create a tuple of colorscolors = ("red", "green", "blue")# Print the tupleprint("Colors:", colors)# Access an element using indexfirst_color = colors[0] # first_color will be "red"print("First color:", first_color)# Trying to modify a tuple element (results in an error)# colors[1] = "yellow" # This will cause an error# You can create a new tuple with modificationsmodified_colors = colors + ("yellow",) # Notice the comma after "yellow" for a single-element tupleprint("Modified colors:", modified_colors)# Slicing works with tuples for extracting a portionsummer_colors = colors[0:2] # summer_colors will be ("red", "green")print("Summer colors:", summer_colors)# Looping through elementsfor color in colors: print("Color:", color)

How to Check a Data Type in Python?

Now that you have a basic understanding of data types let's explore different ways to check an object's data type in Python.

Method 1: Using the type() Function

Python type() is a built-in function that allows you to find the class type of the variable given as input. You have to place the variable name inside the type() function, which outputs the data type.

Here is an example:

a = 60b = "Hello"c = 72.34d = [4, 5, 6]print(type(a)) # Output: <class 'int'>print(type(b)) # Output: <class 'str'>print(type(c)) # Output: <class 'float'>print(type(d)) # Output: <class 'list'>

Method 2: Using the isinstance() Function

The isinstance() function in Python checks if an object belongs to a specific data type or class. It returns a boolean value, True or False, based on whether the object matches the specified type.

Here is an example:

a = 97b = 22.65c = "Python"print(isinstance(a, int))# Output: True print(isinstance(b, float))# Output: True print(isinstance(c, str))# Output: True

Method 3: Using the __class__ attribute

In Python, the __class__ attribute provides information about the class type of an object. Here's an example code that demonstrates how to use the __class__ attribute to obtain the type of a variable:

a = 25print(a.__class__)#<type 'int'> b = "Data"print(b.__class__)#<type 'str'> c = 83.45print(c.__class__)#<type 'float'>Output<class 'int'><class 'str'><class 'float'>

Here are some relevant resources to help you learn more about data types in Python:

Streamlining Data Flows with Airbyte

What Are Data Types in Python With Examples? | Airbyte (1)

Similar to how Python can effortlessly manage various data types like integers and strings, Airbyte can handle diverse data sources adeptly. No matter if it’s structured information from a database or unstructured content from social media, Airbyte can ingest and integrate data from various sources seamlessly into your data workflows.

In addition to its user-friendly interface, Airbyte allows you to incorporate it into your Python workflows using PyAirbyte or API. This allows you to programmatically automate data movement between multiple systems, reduce the need for manual data extraction, and streamline your data management process.

Whether you’re dealing with flat files or cloud storage systems, Airbyte simplifies the process, allowing you to focus on extracting insights.

Here are some of the unique features of Airbyte:

  • Airbyte offers 350+ pre-built connectors for various source and destination systems. This extensive library ensures you to effortlessly transfer data from one platform to another.
  • Airbyte’s PyAirbyte is a Python library that packs most Airbyte connectors into a single code. This streamlines data integration by allowing you to leverage a wide range of connectors for various sources with Python programming.
  • If the pre-built list doesn't cover a specific connector, Airbyte Connector Development Kit (CDK) allows you to build custom connectors using Python.
  • You can specify how Airbyte must handle the source schema changes for each connection. This process helps ensure accurate and efficient data syncs, minimize errors, and save time and effort in handling your data pipelines.

Conclusion

Understanding data types is fundamental to writing effective Python code. By using the appropriate data type for your variables, you ensure data integrity and enable the correct operations on your data. Python offers a variety of built-in data types, including mutable and immutable types, to cater to different needs.

What Are Data Types in Python With Examples? | Airbyte (2024)

References

Top Articles
Latest Posts
Article information

Author: Catherine Tremblay

Last Updated:

Views: 6083

Rating: 4.7 / 5 (67 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Catherine Tremblay

Birthday: 1999-09-23

Address: Suite 461 73643 Sherril Loaf, Dickinsonland, AZ 47941-2379

Phone: +2678139151039

Job: International Administration Supervisor

Hobby: Dowsing, Snowboarding, Rowing, Beekeeping, Calligraphy, Shooting, Air sports

Introduction: My name is Catherine Tremblay, I am a precious, perfect, tasty, enthusiastic, inexpensive, vast, kind person who loves writing and wants to share my knowledge and understanding with you.