0% found this document useful (0 votes)
15 views

Data Type in Python

Uploaded by

VVM
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Data Type in Python

Uploaded by

VVM
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Data Types

Example Data Type

x = "Hello World" str

x = 20 int

x = 20.5 float

x = 1j complex

x = ["apple", "banana", "cherry"] list

x = ("apple", "banana", "cherry") tuple

x = range(6) range

x = {"name" : "Arun", "age" : 36} dict

x = {"apple", "banana", "cherry"} set

x = frozenset({"apple", "banana", "cherry"}) frozenset

x = True bool

x = b"Hello" bytes

x = bytearray(5) bytearray

x = memoryview(bytes(5)) memoryview

x = None NoneType
Setting the Specific Data Type

Example Data Type


x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="Arun", age=36) dict
x = set(("apple", "banana", "apple")) set
x = frozenset(("apple", "banana", frozenset
"cherry"))
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
In Python, there are several built-in collection data types that are useful for
storing and manipulating groups of items. Here’s an overview of the main ones
along with examples:
Lists
Description: Ordered, mutable collections of items. Lists allow duplicates.
Example:
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]
my_list.append(6) # Adds 6 to the end
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

Tuples
Description: Ordered, immutable collections of items. Tuples allow duplicates.
Example:
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple) # Output: (1, 2, 3, 4, 5)
# Tuples are immutable, so you cannot modify them after creation.

Sets
Description: Unordered collections of unique items. Sets do not allow
duplicates and do not maintain order.
Example:
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
my_set.add(6) # Adds 6 to the set
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
my_set.add(3) # No effect, as 3 is already in the set
print(my_set) # Output: {1, 2, 3, 4, 5, 6}

Dictionaries
Description: Unordered collections of key-value pairs. Keys must be unique
and immutable, while values can be of any data type.
Example:
my_dict = {'a': 1, 'b': 2, 'c': 3}
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}
my_dict['d'] = 4 # Adds a new key-value pair
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Collections from the collections module:

NamedTuple
Description: Subclass of tuples with named fields.
Example:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p) # Output: Point(x=10, y=20)
print(p.x) # Output: 10

Deque
Description: Double-ended queue; a list-like container with fast appends and
pops from both ends.
Example:
from collections import deque
d = deque([1, 2, 3])
d.append(4) # Adds 4 to the right end
d.appendleft(0) # Adds 0 to the left end
print(d) # Output: deque([0, 1, 2, 3, 4])
d.pop() # Removes 4 from the right end
d.popleft() # Removes 0 from the left end
print(d) # Output: deque([1, 2, 3])

Counter
Description: A dict subclass for counting hashable objects.
Example:
from collections import Counter
c = Counter('gallahad')
print(c) # Output: Counter({'a': 3, 'l': 2, 'g': 1, 'h': 1, 'd': 1})

OrderedDict
Description: A dict subclass that remembers the order of keys.
Example:
from collections import OrderedDict
d = OrderedDict(a=1, b=2, c=3)
print(d) # Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)])
d.move_to_end('b') # Moves 'b' to the end
print(d) # Output: OrderedDict([('a', 1), ('c', 3), ('b', 2)])

Note: Each of these collection types has its own strengths and is suited for
different use cases, so it's useful to choose the one that best fits the needs of
your application.

In Details

Data Type (Tuple)


Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Create a Python Tuple
numbers = (1, 2, -5)
print(numbers)
Create a Tuple Using tuple() Constructor
tuple_constructor = tuple(('Arun', 'Mars', 'Dev'))
print(tuple_constructor)
Empty Tuple
# create an empty tuple
empty_tuple = ()
print(empty_tuple)
Tuple of different data types
# tuple of string types
names = ('James', 'Jack', 'Eva')
print (names)
# tuple of float types
float_values = (1.2, 3.4, 2.1)
print(float_values)
Tuple of mixed data types
# tuple including string and integer
mixed_tuple = (2, 'Hello', 'Python')
print(mixed_tuple)

Access Items Using Index


languages = ('Python', 'Swift', 'C++')
# access the first item
print(languages[0]) # Python
# access the third item
print(languages[2]) # C++
Tuple Cannot be Modified
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
# trying to modify a tuple
cars[0] = 'Nissan' # error
print(cars)
Python Tuple Length
cars = ('BMW', 'Tesla', 'Ford', 'Toyota')
print('Total Items:', len(cars))
Iterate Through a Tuple
fruits = ('apple','banana','orange')
# iterate through the tuple
for fruit in fruits:
print(fruit)
Check if an Item Exists in the Tuple
colors = ('red', 'orange', 'blue')
print('yellow' in colors) # False
print('red' in colors) # True
Change Tuple Items
fruits = ('apple', 'cherry', 'orange')
# trying to change the second item to 'banana'
fruits[1] = 'banana'
print(fruits)
# Output: TypeError: 'tuple' object does not support item assignment

Delete Tuples
We cannot delete individual items of a tuple. However, we can delete the tuple
itself using the del statement. For example,

animals = ('dog', 'cat', 'rat')

# deleting the tuple


del animals

Create a Python Tuple With One Item


var = ('Hello')
print(var) # string

Data Type (list example)


In Python, a list is a built-in data type used to store an ordered collection of
items. Lists are one of the most versatile and commonly used data structures in
Python due to their flexibility and the wide range of operations that can be
performed on them.
Key Characteristics of Lists
Ordered: Lists maintain the order of elements as they are inserted. This means
the position of each element is preserved.
Mutable: Lists can be modified after they are created. You can add, remove, or
change elements.
Allow Duplicates: Lists can contain duplicate elements.
Indexed: Lists use zero-based indexing, meaning the first element is accessed
with index 0, the second with index 1, and so on.
Creating a List
You can create a list by placing comma-separated values within square brackets
[].

Example Usage
# Creating a list
my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4, 5]

# Accessing elements
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3

# Modifying elements
my_list[1] = 10
print(my_list) # Output: [1, 10, 3, 4, 5]

# Adding elements
my_list.append(6) # Adds 6 to the end of the list
print(my_list) # Output: [1, 10, 3, 4, 5, 6]

# Inserting elements at a specific position


my_list.insert(2, 20) # Inserts 20 at index 2
print(my_list) # Output: [1, 10, 20, 3, 4, 5, 6]

# Removing elements
my_list.remove(10) # Removes the first occurrence of 10
print(my_list) # Output: [1, 20, 3, 4, 5, 6]

# Popping elements (removes and returns an element at a specific position)


popped_element = my_list.pop(3) # Removes element at index 3
print(popped_element) # Output: 4
print(my_list) # Output: [1, 20, 3, 5, 6]

# Slicing lists
sub_list = my_list[1:4] # Gets elements from index 1 to 3 (excluding 4)
print(sub_list) # Output: [20, 3, 5]

# List comprehension
squared_numbers = [x**2 for x in range(5)]
print(squared_numbers) # Output: [0, 1, 4, 9, 16]

# Checking for membership


print(3 in my_list) # Output: True
print(10 in my_list) # Output: False
# Length of the list
print(len(my_list)) # Output: 5
Common List Methods
list.append(x) – Adds an item x to the end of the list.
list.extend(iterable) – Extends the list by appending elements from an iterable.
list.insert(i, x) – Inserts an item x at a given position i.
list.remove(x) – Removes the first occurrence of item x from the list.
list.pop([i]) – Removes and returns the item at the given position i in the list. If
no index is specified, pop() removes and returns the last item.
list.clear() – Removes all items from the list.
list.index(x[, start[, end]]) – Returns the index of the first occurrence of item x.
Raises a ValueError if the item is not found.
list.count(x) – Returns the number of times x appears in the list.
list.sort(key=None, reverse=False) – Sorts the items of the list in place (the
arguments can be used to customize the sort order).
list.reverse() – Reverses the elements of the list in place.
Lists are highly flexible and can store items of different data types, including
other lists, making them a powerful tool for various programming tasks.

Data Type (set example)


fruits = {"Apple", "Banana", "Cherry", "Apple", "Kiwi"}

print('Unique elements:', fruits)


# Add new fruit
fruits.add("Orange")
print('After adding new element:', fruits)

# Size of the set


print('Size of the set:', len(fruits))

# check if the element is present in the set


print('Apple is present in the set:', "Apple" in fruits)
print('Mango is present in the set:', "Mango" in fruits)

# Remove the element from the set


fruits.remove("Kiwi")
print('After removing element:', fruits)
# Discard the element from the set
fruits.discard("Mango")
print('After discarding element:', fruits)

Frozenset
A frozenset in Python is a built-in data type that is similar to a set, but with a
key difference: it is immutable. This means that once a frozenset is created, its
contents cannot be changed—no additions, deletions, or updates are allowed.
This immutability makes frozensets hashable, which means they can be used as
keys in dictionaries or elements in other sets, whereas regular sets cannot.
Key Characteristics of frozenset
1. Immutable: You cannot modify the frozenset after it has been created.
This includes adding or removing elements.
2. Hashable: Because frozenset is immutable, it can be used as a dictionary
key or as an element of another set.
3. Unordered: Like regular sets, frozensets do not maintain order among
elements.
Creating a frozenset
You create a frozenset using the frozenset() constructor, which can take an
iterable (like a list, tuple, or set) as an argument.

numbers1 = frozenset([1, 2, 3, 4, 5])


numbers2 = frozenset([2, 3, 4, 5])
# Combining both of them using "|" operator
# You can also use union() method
combined = numbers1 | numbers2
print("Combined set:", combined)

# Selecting common elements using "&" operator


# You can also use intersection() method
intersect = numbers1 & numbers2
print("Intersected set:", intersect)

# Selecting elements which are not common using "-" operator


# You can also use difference() method
difference = numbers1 - numbers2
print("Difference set:", difference)
# Membership testing

# It returns True if sets (frozenset) have no common items otherwise False


Disjoint = numbers1.isdisjoint(numbers2)
print("Disjoint:", Disjoint)

# It returns True if all the items of a set (frozenset) are common in another set
(frozenset)
Subset = numbers1.issubset(numbers2)
print("Subset:", Subset)

# It returns True if a set (frozenset) has all items present in another set
(frozenset)
Superset = numbers1.issuperset(numbers2)
print("Superset:", Superset)

Note : frozenset is particularly useful when you need an immutable,


unordered collection of unique elements, especially when using such
collections as dictionary keys or set elements.

You might also like