0% found this document useful (0 votes)
4 views15 pages

05.array in Python

The document provides an overview of data structures in Python, including arrays, lists, tuples, and dictionaries. It explains the characteristics, features, and common operations associated with each data structure, highlighting the differences between them. Additionally, it introduces the NumPy library for advanced array handling and mathematical operations.

Uploaded by

124421amritraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views15 pages

05.array in Python

The document provides an overview of data structures in Python, including arrays, lists, tuples, and dictionaries. It explains the characteristics, features, and common operations associated with each data structure, highlighting the differences between them. Additionally, it introduces the NumPy library for advanced array handling and mathematical operations.

Uploaded by

124421amritraj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Definition

 In Python, arrays are collections that store multiple items of the


same/different data types depending on the array type used in Python.

Features

 Unlike C or Java, Python has no built-in array data type. Instead,


Python provides alternatives like lists and the array module for arrays.

Types of Arrays in Python

(A) Array Module in Python

 An Array Module is a basic array that is more memory efficient than


lists but requires homogeneous data.
 If we need an actual array in Python, the array module provides an
array object that only stores elements of the same data type (e.g.,
integers, floats).
 In Python, the array module does not support storing strings directly
because it is designed for storing numeric values or characters (single-
character Unicode).
 For creating the array Module, we use – import array.
 For example –

import array
# To create an array of integers
array1 = [Link](‘i’, [1, 2, 3, 4, 5])
print(array1[0]) # Output: 1

 Features of the Array Module


o Arrays are more efficient than lists when working with large
collections of the same data type.
o It requires specifying the type of the array elements using type
codes (e.g., ‘i’ for integers, ‘f’ for floats).
 Common Type Codes in Array

Type Code C Type Python Type


'b' signed char int
'B' unsigned char int
'i' signed int int
'f' float float
'd' double double

 Common Operations with Arrays

There are the following types of common operations in the Array Module –

o Accessing elements
 print(array1[1]) # Second element: 2
o Appending an element
 [Link](6) # array(‘i’, [1, 2, 3, 4, 5, 6])
o Inserting at a specific index
 [Link](2, 10) # array(‘i’, [1, 2, 10, 3, 4, 5, 6])
o Removing elements
 [Link](10) # array(‘i’, [1, 2, 3, 4, 5, 6])
 Looping through an array

for x in array1:
print(x)

(B) Lists in Python


 Lists are mutable dynamic structures and can store multiple elements
of different data types, making them a common
substitute for arrays in Python.
 They are not as memory-efficient as real arrays when
dealing with large datasets of uniform type.
 This array is used for basic, flexible data structures and is defined
using a [ ] symbol.
 Unlike tuples, they are mainly used when we want data to change in
an application.
 For example –

list1 = [10, 20, 30, 40, 50] # This is the List of integers.
print(list1[0]) # Accessing the first element of list.
print(list1[2]) # Accessing the third element of list.

 Features of Lists:
o Lists can store multiple elements of different types.
o The Lists elements are mutable (can change their elements).
o The Lists can grow or shrink dynamically.
 Common Operations and Methods Associated with the Lists:
o Accessing the elements
 print(list1[0]) # Accessing first element: 10
o Appending an element
 [Link](60) # [10, 20, 30, 40, 50, 60]
o Inserting at a specific index
 [Link](1, 70) # [10, 70, 20, 30, 40, 50, 60]
o Removing elements
 [Link](70) # [10, 20, 30, 40, 50, 60]
o Slicing a list
 print(list1[1:4]) # [20, 30, 40](B) Array Module in Python
 An Array Module is a basic array that is more memory efficient than
lists but requires homogeneous data.
 If we need an actual array in Python, the array module provides an
array object that only stores elements of the same data type (e.g.,
integers, floats).
 For importing the array Module, we use – import array.
 For example –

import array
# To create an array of integers
array1 = [Link](‘i’, [1, 2, 3, 4, 5])
print(array1[0]) # Output: 1

 Features of the array Module


o Arrays are more efficient than lists when working with large
collections of the same data type.
o It requires specifying the type of the array elements using type
codes (e.g., ‘i’ for integers, ‘f’ for floats).
 Common Type Codes in Array

Type Code C Type Python Type


'b' signed char int
'B' unsigned char int
'i' signed int int
'f' float float
'd' double float

 Common Operations with Arrays

There are the following types of common operations in the Array Module –
o Accessing elements
 print(array1[1]) # Second element: 2
o Appending an element
 [Link](6) # array(‘i’, [1, 2, 3, 4, 5, 6])
o Inserting at a specific index
 [Link](2, 10) # array(‘i’, [1, 2, 10, 3, 4, 5, 6])
o Removing elements
 [Link](10) # array(‘i’, [1, 2, 3, 4, 5, 6])
 Looping through an array

for x in array1:
print(x)

(C) Tuple in Python

 Definition
o Tuples in Python are immutable(not changeable), ordered
collections of data items of the same/different types, used when
the user wants to group related data that should not be
modified.
 Characteristics
o They are indexed, i.e, like lists, tuple elements are accessed
using indices starting from 0.
o They are similar to lists, but unlike lists, tuples cannot be
modified after they are created.
o They are faster in operations(because of immutability) than
Lists.
o They are mainly used when we don’t want data to change in an
application.
o They offer efficient access to data and are often used in cases
where immutability is essential, such as returning multiple
values from functions or using them as dictionary keys.
 Advantages
o Since a Tuple is an ordered collection of items, it maintains the
order of elements.
o They are Heterogeneous, i.e., Tuples can store elements of
different data types (e.g., integers, strings, floats) as needed.
o Tuples are often used to group related data, and their
immutability can be useful when we want to ensure that certain
data remains unchanged throughout a program.

 Disadvantages

o They are immutable, i.e., once a tuple is created, its contents


cannot be changed (no adding, removing, or modifying
elements). It may be advantageous in a few cases also.

 To Create Tuples

o We can create a tuple by enclosing


values in parentheses ()` and separating them with commas.
o For example –
 x = (10, 20, 30, 40, 50) # Tuple with same data types.
 y= (10, “Hello India”, 3.141, True) # Tuple with different
data types/mix tuple/hybrid tuple.
 z= (50,) # Single-element tuple (requires a trailing
comma), without the comma, it’s just an integer.
 k = () #Empty tuple
 Accessing Tuple Elements
o We can access individual elements of a tuple using
indexing or retrieve multiple elements using slicing.
o For Example:
 x = (10, 20, 30, 40, 50, 60, 70, 80, 90)

# Accessing an element
print(x[0]) # Output: 10 (first element)
# Negative indexing
print(x[-1]) # Output: 90 (last element)
# Slicing a tuple
print(x[1:5]) # Output: (20, 30, 40, 50)
print(x[3:6]) # Output: (40, 50, 60)

 Tuple is Immutable: Since tuples are immutable, we


cannot change their content after creation. For example,
trying to assign a new value to an index will raise an error.
For example:-

x = (1, 2, 3)
x[0] = 10 # This will raise a TypeError: ‘tuple’ object
does not support item assignment

 Creating and accessing tuple elements

person = (“Romi”, 25, “Doctor”)


# Accessing tuple elements
name = person[0]
age = person[1]
profession = person[2]
print(f“Name: {name}, Age: {age},
Profession: {profession}“)
# Output: Name: Romi, Age: 25, Profession: Doctor
 Tuple Operations
o Concatenation: We can concatenate two or more tuples using
the `+` operator.

tuple1 = (10, 20)


tuple2 = (30, 40)
result = tuple1 + tuple2
print(result) # Output: (10, 20, 30, 40)

o Repetition: We can repeat the contents of a tuple using


the `*` operator.

x= (10, 20)
print(x * 3) # Output: (10, 20, 10, 20, 10, 20)

o Membership Testing: We can check if an item is present in a


tuple using the `in` keyword.

x= (10, 20, 30, 40)


print(30 in x) # Output: True
print(50 in x) # Output: False

 Tuple Methods

Since tuples are immutable, they have comparatively fewer methods than
Lists, mainly for querying.

o count():
 This method returns the number of occurrences of a
specific value in the tuple.
 For example –

x = (10, 20, 30, 10, 10)


print([Link](10)) # Output: 3

o index():
 This method returns the index of the first occurrence of
that specified value.
 For example –

x = (10, 20, 30, 40)


print([Link](30)) # Output: 2

 Packing and Unpacking Tuples


o Tuple Packing
 The assignment of multiple values (of different types) to a
tuple in a single statement is called packing.
 For example –

x = 1, 2, “apple”, 3.5 # Parentheses are optional


print(x) # Output: (1, 2, ‘apple’, 3.5)

o Tuple Unpacking
 We can also unpack a tuple into individual variables.
 For example –

x = 1, 2, “apple”, 3.5
a, b, c, d = x
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: apple
print(d) # Output: 3.5

 Unpacking with a wildcard (`*`): We can use `*` to unpack


the remaining values into a list.
x = (10, 20, 30, 40, 50)
a, b, *rest = x
print(a) # Output: 10
print(b) # Output: 20
print(rest) # Output: [30, 40, 50]

 Use of Tuples
o Return Multiple Values from Functions
 Tuples are often used to return multiple values from a
function.
 For example –

def Method1():
return (30, 70)
temp, humidity = Method1() #assigns two
values

o Immutable Grouping of Related Data


 If we want to group related items and ensure they don’t
change, a tuple is used.
 user_profile = (“Rani”, 18, “Student”)
o Keys in Dictionaries:
 Tuples can be used as keys in dictionaries, whereas lists
cannot because tuples are immutable and washable.
 For example –

my_dict = {(1, 2): “Point A”, (3, 4): “Point B”}

(D) NumPy Arrays (Advanced)

 NumPy is a powerful library for handling large, multi-dimensional


arrays with efficient mathematical operations in Python.
 The NumPy library is often used in Python for more efficient and
complex array operations.
 NumPy provides multi-dimensional arrays and high-level
mathematical functions unavailable in basic lists or the array module.
 This array is used for high-performance numerical computation
mainly.
 For Installing NumPy

pip install numpy

 To Create a NumPy Array

import numpy as np
# Creating a 1D array
arr = [Link]([1, 2, 3, 4, 5])
print(arr) # Output: [1 2 3 4 5]
# Creating a 2D array (matrix)
matrix = [Link]([[1, 2], [3, 4]])
print(matrix)

 Features of NumPy Arrays


o Homogeneous: All elements in a NumPy array must be of the
same type.
o Supports multi-dimensional arrays
(e.g., 2D arrays or matrices).
o Optimized for numerical operations, making it much faster than
lists for mathematical calculations.
 Common NumPy Operations
o Accessing elements
 print(arr[0]) # Output: 1
o Performing mathematical operations
 print(arr * 2) # Element-wise multiplication: [2 4 6 8 10]
 Reshaping arrays: We can convert 1D into 2D as needed using
NumPy Arrays.
o array2 = [Link](5, 1) # Convert 1D array into 2D array
with 5 rows and 1 column

 Matrix multiplication using NumPy Array

import numpy as np

matrix1 = [Link]([[1, 2], [3, 4]])


matrix2 = [Link]([[5, 6], [7, 8]])
result = [Link](matrix1, matrix2)
print(result) # Output: [[19 22] [43 50]]

Dictionary in Python

 A dictionary in Python is a collection of data items in key–


value pairs form.
 Each value is accessed using its key, not its index. Key can be a string,
a number, or a tuple.
 Keys must be unique and of any type/value.
 Values can also be any data type/anything, such as int, list, dict,
string, etc.
 Dictionaries’ values can be unordered, i.e., do not follow an index like
a list.
 Dictionaries are created using curly braces {}.
 Values can be accessed using a key.
 Dictionary value can be modifiable (mutable).
 Dictionary values have very fast lookup.
 For example –
#creation of a dictionary
my_dict = {
“name”: “Rahul”,
“age”: 21,
“city”: “Patna”
}
Here, my_dict is the name of the dictionary,
name, age, and city are the Key
Rahul, 21, and Patna are the respective Value.

 To access the Dictionary values –

student = {“name”: “Anita”, “age”: 20}

print(student[“name”]) # Anita
print(student[“age”]) # 20

 To add a new key-value pair to a dictionary –

student[“course”] = “BCA”

 To print a key-value in a dictionary –

student = {“name”: “Anita”, “age”: 20}

for i in student:
print(i) #print only keys
Output:
name
age
————- OR ————-
student = {“name”: “Anita”, “age”: 20}
for i in [Link]():
print(i) #print only values
Output:
Anita
20
————- OR ————-
student = {“name”: “Anita”, “age”: 20}

print(student[“age”])
#print([Link](“age”))
Output:
20
————- OR ————-
student = {“name”: “Anita”, “age”: 20, “class”:10}

print(student[“age”], student[“name”])
Output:
20 Anita
————- OR ————-
student = {“name”: “Anita”, “age”: 20}

for i, j in [Link]():
print(i, “=”, j) # print both key and values
Output:
name = Anita
age = 20
————- OR ————-
student = {“name”: “Anita”, “age”: 20}
for i, j in [Link]():
print(f“{i}: {j}“) #print both key and values in customized
format
Output:
name: Anita
age: 20

 To update a value in a dictionary –

student[“age”] = 30

 To delete a key-value in a dictionary –

[Link](“age”) # removes key ‘age’


[Link]() # removes last inserted key-value
del student[“name”] # deletes key
[Link]() # empties all data of dictionary

You might also like