Home » Data Types in Python

Data Types in Python

Data Types in Python

What are Data Types in Python?

Data types in Python are an essential concept in programming, defining the kind of data a variable can hold. They determine the values a variable may contain and the operations that can be performed on it. Understanding data types in python is crucial for effective programming, as it influences how data is stored, processed, and manipulated within a program.

Data Types in Python

In Python, every value is associated with a specific data type. Since Python treats everything as objects, these data types are essentially classes, with variables acting as instances (objects) of these classes.

Python provides a range of data types, each fulfilling different roles within the language.

Python supports various data types, classified into several categories:

Data TypeDescription
Numeric Typesint, float, complex
Sequence Typeslist, tuple, range
Mapping Typedict
Set Typesset, frozenset
Boolean Typebool
Text Typestr
Binary Typesbytes, bytearray, memoryview

List of Data Types in Python are below

1. Python Numbers

In Python, integers, floating-point numbers, and complex numbers are grouped together as Python numbers. These numeric types are represented by the int, float, and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to.

Similarly, the isinstance() function is used to check if an object belongs to a particular class.

a1= 5
print(a1, "is of type", type(a1))
print(a1, "is integer number?", isinstance(5,int))

a2= 2.0
print(a2, "is of type", type(a2))
print(a2, "is float number?", isinstance(2.0,float))

a3= 1+2j   # '1' is real part and '2j' is imaginary part
print(a3, "is of type", type(a3))
print(a3, "is complex number?", isinstance(1+2j,complex))
Python

Output:

5 is of type <class 'int'>
5 is integer number? True
2.0 is of type <class 'float'>
2.0 is float number? True
(1+2j) is of type <class 'complex'>
(1+2j) is complex number? True
Python

Integers in Python can be as long as your computer’s memory allows, meaning they can be very large.

a = 1234567890123456789
print (a)
Python

Output:

1234567890123456789
Python

On the other hand, floating-point numbers (or decimals) are precise up to 15 digits after the decimal point. The main difference between integers and floating-point numbers is the presence of a decimal point; for instance, ‘1’ is an integer, while ‘1.0’ is a floating-point number.

f = 0.1234567890123456789  # total of only 17 numbers after decimal can be printed.
print (b)
Python

Output:

0.12345678901234568
Python

Notice that the float variable f got truncated.

Complex numbers are expressed as ‘x + yj,’ where ‘x’ is the real portion and ‘y’ is the imaginary part. Here are a few examples to illustrate these points.

c = 1+2j
print (c)
Python

Output:

(1+2j)
Python

2. Python List[]

Python lists are like flexible containers where you can keep and organize your items, such as numbers, words, or even other lists. Let’s break down what makes Python lists so useful, in simpler terms.

What is a Python List?

Think of a list as a row of boxes, where each box can hold something different. You can rearrange the boxes, take items out, add new ones, or even look inside a specific box whenever you want.

How to Make and Use Lists

Creating a list is easy. Just put the items you want to keep together between square brackets [ ], like so:

my_pets = ['dog', 'cat', 'fish']
Python

If you want to see what’s in the first box (Python starts counting from 0), you do this:

print(my_pets[0])  # This shows: dog
Python
Changing Lists

Lists are great because you can change them after you make them:

  • Adding Items: You can add more pets to your list: pythonCopy code my_pets.append('bird') # Now you have a bird too!
  • Taking Items Out: If you no longer have the fish, you can remove it: pythonCopy code my_pets.remove('fish') # Now the fish is gone.
Walking Through Lists

You can look at each pet in your list one by one with a loop, which is like walking along the row of boxes and looking inside each:

for pet in my_pets:
    print(pet)
Python
Making Lists Quickly

Python has a cool trick called a list comprehension that lets you make a new list by changing each item in an old list or picking only certain items. For example, making a list of the first 10 square numbers:

squares = [number**2 for number in range(10)
Python
Lists Inside Lists

You can even put lists inside other lists, like stacking boxes within boxes:

my_stuff = ['book', ['pen', 'pencil'], 'notebook']
Python

3. Python Tuple ()

Python tuples are like lists because they can hold a bunch of items together. However, they have a few key differences that make them unique. Here’s how to understand tuples in a simple and straightforward way.

What is a Python Tuple?

Imagine a tuple as a bookshelf where you’ve placed different items (like books, CDs, and photos) in a specific order. Once you set up your shelf, you can’t add new items or take any away; you can only look at them or use them as they are. This is because tuples are immutable, which means once you create them, they cannot be changed.

How to Make and Use Tuples

You create a tuple by putting items inside parentheses ( ), separated by commas:

my_favorites = ('pizza', 'chocolate', 'movies')
Python

To see what’s in the second spot on your shelf (remember, counting starts at 0), you do this:

print(my_favorites[1])  # This shows: chocolate
Python
The Big Difference: You Can’t Change Them

Unlike lists, you can’t add to or remove items from a tuple once it’s made. This might seem like a downside, but it’s actually useful in certain situations, especially when you want to make sure nothing gets accidentally changed.

Walking Through Tuples

Just like with lists, you can go through each item in a tuple one by one:

for item in my_favorites:
    print(item)
Python
When to Use Tuples

Since tuples can’t be changed, they’re great when you have a collection of items that you want to stay the same throughout your program. They’re often used for things like storing coordinates on a map or the days of the week—things that you know won’t need to be altered.

Tuples vs. Lists

To sum it up, if you want a collection of items that won’t change, use a tuple. If you think you’ll need to add, remove, or change items, then a list is what you’re looking for.

Tuples are like snapshots of a collection of items: once you take the picture, it stays the same forever. This can be really handy for making sure some parts of your program stay constant and error-free.

In essence, tuples are perfect for keeping a safe, unchangeable record of items in your Python programs!

4. Python String

Imagine a string as a train where each carriage is a letter, number, or symbol. This train of characters can tell a story, display a message, or represent data in your program.

How to Make and Use Strings

Creating a string is as easy as writing text between quotes:

greeting = "Hello, world!"
Python

You can look at each ‘carriage’ (character) by using its position in the train:

print(greeting[0])  # This shows: H</mark>
Python
Changing Strings

Strings are immutable, like tuples, meaning once you create them, you can’t change the individual characters. But you can combine strings together or make new strings from parts of others:

name = "Alice"
message = greeting + " " + name + "!"
print(message)  
Python

Output:

Hello, world! Alice!
Python

Strings are how you handle text in your programs. Whether you’re asking for input, showing messages, or working with files, you’ll use strings to communicate with users and handle text data.

5. Python Set

Think of a set as a basket of fruit where each piece of fruit is different. Just like you can’t have two identical apples in the same basket in Python sets, you can’t have duplicate items.

How to Make and Use Sets

You create a set by putting items inside curly braces { }, or by using the set() function:

pythonCopy code
fruits = {'apple', 'banana', 'cherry'}
Python

Sets are unordered, so you can’t access items by an index. But you can check if an item is in the set, add new items, or remove items:

'apple' in fruits  # Checks if 'apple' is in the set, 
returns True or False
fruits.add('orange')  # Adds 'orange' to the set
fruits.remove('banana')  # Removes 'banana' from the set
Python

Sets are useful when you need to keep track of unique items, like tags on a blog post or unique users visiting a website.

6. Python Dictionary

A dictionary in Python is like a real dictionary but for your data. Think of it as a big book of words (keys) where each word has a definition (value) attached. You use the key to find the value, just like looking up a word to find its meaning.

How to Make and Use Dictionaries

Creating a dictionary involves pairing keys and values within curly braces {}:

my_pet = {'type': 'dog', 'name': 'Rex', 'age': 5}
Python

You can access a value by using its key:

print(my_pet['name'])  # This shows: Rex
Python
Changing Dictionaries

Dictionaries are mutable, so you can add new key-value pairs, change values, or remove them:

my_pet['color'] = 'brown'  # Adds a new key-value pair
my_pet['age'] = 6  # Updates the value for 'age'
del my_pet['type']  # Removes the key-value pair for 'type'
Python

Dictionaries are incredibly versatile for organizing data in your programs. They’re great for storing and quickly accessing data like settings, records, or configurations by key.