DEV Community


Posted on

Introduction to Python Data Types

Myself Ram started my Data Science course and completed the below concepts in last 4 weeks. I am planning to write on monthly basis what I have learned in this journey. Let's get started

In this post , I will be covering example for Python Data Types.

Variables are names given to data items that may take on one or more values during a program’s runtime.


It cannot begin with a number.
It must be a single word.
It must consist of letters and _ symbols only.

val = 10       # val is of type int
name = "Sally" # name is now of type str
name = 10      # name is now of type int
Enter fullscreen mode Exit fullscreen mode

Data Types:
Python has built-in data types that allows us to store different type of values. In Python, the data type is set when you assign a value to a variable:

  1. Integers are whole numbers like 1,2,3,0,-1,-2,-3. They can be positive, negative or 0. Integers are immutable in Python
x = 10    # positive integer
y = -5    # negative integer 
print(type(x)) # <class 'int'>
print (x + y) # 5
print (x - y) # 15
print (x * y) # -50
Enter fullscreen mode Exit fullscreen mode
  1. Floats represent real numbers like -1.5, -0.4, 0.0, 1.25, 9.8 etc. float() adds a decimal point to the number. Floating point numbers always have at least one decimal place of precision.
x = 3.14
y = 5.0
Enter fullscreen mode Exit fullscreen mode
  1. Boolean Type Boolean represents logical values True and False. Useful for conditional testing and logic. For example: x = True y = False Boolean operators like and, or, not can be used to compose logical expressions and conditions.

String represent sequences of unicode characters like letters, digits, spaces etc. They are immutable in Python. String objects can be accessed through Index position . Index starts from 0.

String support operations like concatenation, slicing, length etc. Format specifiers like %s can be used for formatting for custom needs

str1 = 'Welcome'
print(str1[0]) # W
Str1 = 'Welcome to '
str2 = 'Python'
print(Str1 + str2) # Welcome to Python
Str3 = 'NewYork'
print(I Live in  %s' % name) # I Live in NewYork

Enter fullscreen mode Exit fullscreen mode


  1. Lists are the most basic data structure available in python that can hold multiple variables/objects together for ease of use.

2.Lists are mutable - you have the ability to change the values
You can access the values in the list through index.

3.When you specify the index range [ from : to] , the "to" index position is not included in the output.

L = ["Chemistry", "Biology", [1989, 2004], ("Oreily", "Pearson")]
L[0] # Chemistry
print(len(L)) #4
L[0:2] # "Chemistry", "Biology"
Enter fullscreen mode Exit fullscreen mode

Extend -> Takes each item in the list and adds one by one
Append -> Takes the whole list that needs to be added and adds as single item
Sort -> L.Sort()
Reverse Sort -> L.Sort(Reverse = True)

Sort vs Sorted

sort(): Sorts the elements of a list in place
sorted(): Assign the sorted elements to a new list and the original list is left as is.

Shadow Copy:

B=A -> Shadow Copying. Any update we make in A will be reflected in B
B=A[:] -> It copies all the elements from A to B. Updates in A is not reflected in B

How to remove duplicate values in List

Couple of Options
1. Convert to set.  s = set(list) . stores the unique variable in the set.
2. result = []
for i in test1:
    if i not in result:
print (result)
Enter fullscreen mode Exit fullscreen mode


Tuples are ordered collections of values that are immutable. Allows storing different data types.
We can access elements using an index but cannot modify tuples.
Tuples support operations like concatenation, slicing, length etc.

thistuple = ("apple", "cherry","banana",123,[1,2,3])
print(len(thistuple)) # 4

A range represents an immutable sequence of numbers. It is commonly used to loop over sequences of numbers. Ranges are often used in for loops:

nums = range(3) # 0 to 2 
print(list(nums)) # [0, 1, 2]

for i in range(3):
# Output:
# 0
# 1  
# 2
Enter fullscreen mode Exit fullscreen mode

create ranges with a start, stop, and step size.

nums = range(3, 8, 2) 
print(list(nums)) # [3, 5, 7]

Enter fullscreen mode Exit fullscreen mode

Sets are unordered collections of unique values. They support operations like membership testing, set math etc.
Sets contain unique values only. Elements can be added and removed.

thisset = {"apple", "banana", "cherry"}

Enter fullscreen mode Exit fullscreen mode

Set math operations like union intersection work between sets.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # {1, 2, 3, 4, 5}
print(set1 & set2) # {3}

Frozenset is an immutable variant of a Python set. Elements cannot be added or removed.
colors = frozenset(['red', 'blue', 'green'])


Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

student = {
  'name': 'Ram',
  'age': 30, 
  'courses': ['CSE', 'ECE']
student['name'] = 'Krish' # update value
print(student['courses']) # ['CSE', 'ECE']

# Add new Keys
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
thisdict.update({"color": "red"})

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}

x = thisdict.keys()       # List all the keys in the dictionary

# Access data in the dictionary
for key in student:
    print(key, student[key]) # print each items

# To remove items
del thisdict["model"] # Remove data by Keys
thisdict.popitem() #Removes last added item or random item
thisdict.pop("model") # Removes item by key
thisdict.clear() #Clears all the values in the dictionary
del thisdict # Deletes the dictionary
Enter fullscreen mode Exit fullscreen mode

The None keyword is used to define a null value, or no value at all.
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

x = None

if x:
  print("Do you think None is True?")
elif x is False:
  print ("Do you think None is False?")
  print("None is not True, or False, None is just None...")

"None is not True, or False, None is just None..."
Enter fullscreen mode Exit fullscreen mode

Summary of Data Types:
Image description

Image description

Please review the contents and post your comments. if there is areas of improvement, feel free to comment. I need to keep improving on my content quality

Top comments (0)