Data Structures

Introduction to Sequence data type in python

sequences are a fundamental data type that represent an ordered collection of items. They allow for indexing, slicing, and iterating over elements. The most common sequence types in Python are strings, lists, tuples, and ranges. Each of these types has its own characteristics and uses, but they all share some common operations and behaviors.
The following subcategories of sequence data type:
1.String 2.List
3.Tupple 4.Set
5.Range 6.Bytes
7.Bytes array

1.List:

A list is a mutable sequence that can hold items of any data type. Lists are dynamic and can be changed after creation. A list is a collection of things, enclosed in [ ] and separated by commas. 
Syntax:
listobj[b1,b2]
b=[]
Example:
numbers = [1, 2, 3, 4, 5]
mixed = [1, “bhanu”, 3.0, [4, 5]]
print(mixed)
print(numbers)

Basic list operations on List

Accessing Elements

people = ["Bhanu", "akhil", "yaswanth"]
# Accessing Elements by Index
b= people[0] # "Bhanu"

Negative Indexing

people = ["Bhanu", "akhil", "yaswanth"]
# Accessing the last element using negative indexing
b = people[-1] # "akhil"

Slicing

people = ["Bhanu", "akhil", "yaswanth"]
# Slicing the list to get a sublist
bhanu_people_slice = people[0:2] # ["Bhanu", "akhil"]

Modifying Elements

people = ["Bhanu", "akhil", "yaswanth"]
# Modifying the second element
people[1] = "Charlie"
# Resulting list: ["bhanu","Charlie", "yaswanth"]

Appending

people = ["Bhanu", "akhil", "yaswanth"]
# Appending "Bhanu" to the end of the list
people.append("Bhanu")
# Resulting list: ["bhanu", "Akhil", "yaswanth", "Bhanu"]

2. Inserting

people = ["Bhanu", "akhil", "yaswanth"]
# Inserting "Bhanuprakash" at the second position
people.insert(1, "Bhanuprakash")
# Resulting list: ["Bhanu", "bhanuprakash","akhil", "yaswanth", "Bhanu"]

3. Extending

people = ["Bhanu", "akhil", "yaswanth"]
# Extending the list with another list containing "Bhanu"
people.extend(["David", "Bhanu"])
# Resulting list: ["Bhanu", "akhil", "yaswanth", "David", "Bhanu"]

Removing Elements

1. Removing by Value

people = ["Bhanu", "akhil", "yaswanth"]
# Removing the first occurrence of "Bhanu"
people.remove("Bhanu")
# Resulting list: ["akhil", "yaswanth",]

2. Removing by Index

people = ["Bhanu", "akhil", "yaswanth"]
# Removing the element at index 2
b= people.pop(2)
# Resulting list: ["Bhanu","akhil"]
# Popped element: "yaswanth"

3. Clearing

people = ["Bhanu", "akhil", "yaswanth"]
# Clearing the entire list
people.clear()
# Resulting list: []

List Slices

List slicing in Python is a powerful feature that allows you to extract specific parts of a list to create a new list. Slicing involves specifying a range of indices and is often used for creating sublists, reversing lists, and skipping elements.

Syntax of List Slicing
The basic syntax for slicing a list is:
list[start:stop:step]
start: The index where the slice begins (inclusive). Defaults to the beginning of the list if omitted.
stop: The index where the slice ends (exclusive). Defaults to the end of the list if omitted.
step: The interval between elements in the slice. Defaults to 1 if omitted.
Example:
names = [“Bhanu”, “Akhil”, “Yaswanth”, “Bhanu”, “Akhil”, “Yaswanth”]
Extracting a sublist from index 1 to 3

b = names[1:4] 
print(b) # ["Akhil", "Yaswanth", "Bhanu"]

Explanation: This slice includes elements from index 1 to 3 (i.e., "Akhil," "Yaswanth," and "Bhanu") but excludes the element at index 4.

Example: Extracting from the beginning up to index 2

names = ["Bhanu", "Akhil", "Yaswanth", "Bhanu", "Akhil", "Yaswanth"]
b = names[:3] 
print(b) # ["Bhanu", "Akhil", "Yaswanth"]
Explanation: Omitting the start index includes elements from the beginning of the list up to, but not including, index 3.

Mutability:

Mutability is an important concept in Python programming that determines whether an object’s state or value can be changed after it has been created. In Python, some objects are mutable, meaning their values can be altered, while others are immutable, meaning they cannot be changed once created.
Example using real life scenario
Scenario: Shopping List
Imagine you have a shopping list written on a piece of paper. You can add, remove, or change items on the list easily. This paper shopping list is a good analogy for a mutable object in Python.
Example: Lists

Lists are mutable, which means you can modify their content directly.

# Creating a list of names
names = ["Bhanu", "Akhil", "Yaswanth"]

# Modifying an element in the list
names[0] = "Ravi"
print(names) # ["Ravi", "Akhil", "Yaswanth"]

# Adding an element to the list
names.append("Sita")
print(names) # ["Ravi", "Akhil", "Yaswanth", "Sita"]

# Removing an element from the list
names.remove("Akhil")
print(names) # ["Ravi", "Yaswanth", "Sita"]

# Changing a slice of the list
names[1:3] = ["Kiran", "Nisha"]
print(names) # ["Ravi", "Kiran", "Nisha"]

Aliasing:

Aliasing occurs when two or more variables refer to the same object in memory. This means that changes made to the object through one alias will be reflected in the other.
Example using real life scenario:
Scenario: Shared Shopping Cart

Imagine a scenario where two friends, bhanu and akhil, share a shopping cart for online groceries. Both have access to the same cart, so any item added or removed by one person is visible to the other.
Example:

# Alice and Bob share a shopping cart
alice_cart = ["apples", "bananas", "milk"]

# Bob's cart is an alias of Alice's cart
bob_cart = alice_cart

# Alice adds an item to the cart
alice_cart.append("bread")
print("Alice's Cart:", alice_cart)  # ["apples", "bananas", "milk", "bread"]
print("Bob's Cart:", bob_cart)      # ["apples", "bananas", "milk", "bread"]

# Bob removes an item from the cart
bob_cart.remove("bananas")
print("Alice's Cart after Bob's update:", alice_cart)  # ["apples", "milk", "bread"]
print("Bob's Cart after Bob's update:", bob_cart)      # ["apples", "milk", "bread"]

Explanation:
Both alice_cart and bob_cart point to the same list object in memory. When Alice adds "bread," it appears in Bob's cart, and when Bob removes "bananas," it is also removed from Alice's cart. This is because both variables are aliases for the same list.

Cloning

Cloning a list in Python means creating a copy of the list so that modifications to the new list do not affect the original list. This is especially important when dealing with mutable objects, as direct assignments can lead to aliasing, where multiple variables reference the same object in memory.
Using slicing to clone a list in Python is a straightforward and commonly used technique. The slicing notation [:] creates a shallow copy of the list, meaning that while the new list itself is a separate object, the elements within the list are still references to the same objects as in the original list.
Example:
names = [“Bhanu”, “Akhil”, “Yaswanth”]
cloned_names = names[:] # Modifying the cloned list
cloned_names.append(“charan”)
print(“Original List:”, names) # [“Bhanu”, “Akhil”, “Yaswanth”]
print(“Cloned List:”, cloned_names) # [“Bhanu”, “Akhil”, “Yaswanth”, “charan”]

Explanation:
creates a new list that contains all elements from the original names list. This new list (cloned_names) is a separate object with its own memory address
Modifications to cloned_names (like appending “Ravi”) do not affect the original names list.
names[:].

List parameters

when you work with functions and lists, you can use various methods to pass lists as parameters and manipulate them. Understanding how to pass and use lists as function parameters can help you write more flexible and reusable code.
There are two types of parameters in python:
1.Formal parameters
2.Acutal parameters

1. Formal Parameters

Definition: Formal parameters are the variables listed in the function definition. They act as placeholders for the values that will be passed to the function when it is called.

Purpose: They define the number and type of arguments that the function expects. Formal parameters are used within the function to perform operations on the data provided by the actual parameters.

Example:

def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet("bhanu",19)
# Function definition:
# 'name' and 'age' are formal parameters

2. Actual Parameters

Definition: Actual parameters (also known as arguments) are the real values or expressions passed to the function when it is called. They correspond to the formal parameters and are used to provide the specific data that the function operates on.

Purpose: They supply the actual values that the function needs to perform its operations. These values are assigned to the formal parameters when the function is invoked.

Types of arguments :
1.Defalut arguments
2.Required arguments
3.keyword arguments
4.Arbitrary arguments

1. Positional Arguments

Definition: Positional arguments are the most basic type of arguments. They are passed to the function in the order that the parameters are defined.

Example:

pythonCopy codedef greet(name, age):
print(f"Hello {name}, you are {age} years old.")

# Calling the function with positional arguments
greet("Bhanu", 19)

Explanation:

  • "Bhanu" is passed as the name parameter.
  • 30 is passed as the age parameter.
  • The order of the arguments matters.

2. Keyword Arguments

Definition: Keyword arguments specify which parameter you are passing a value to by using the parameter name in the function call. This allows you to provide arguments in any order and improves code readability.

Example:

pythonCopy codedef describe_person(name, age, occupation):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Occupation: {occupation}")

# Calling the function with keyword arguments
describe_person(age=28, name="Alice", occupation="Engineer")

Explanation:

  • Here, name, age, and occupation are explicitly assigned values, allowing you to pass arguments in any order.

3. Default Arguments

Definition: Default arguments are parameters that have default values. If a value for such a parameter is not provided in the function call, the default value is used.

Example:

def greet(name, age=25):
print(f"Hello {name}, you are {age} years old.")

# Calling the function with one argument
greet("Bhanu") # Uses default age value

# Calling the function with both arguments
greet("Akhil", 30)

Explanation:
age has a default value of 25. If no value is provided for age, 25 is used.

4. Variable-Length Arguments

Definition: Variable-length arguments allow you to pass a variable number of arguments to a function. Python provides two types of variable-length arguments: *args for positional arguments and **kwargs for keyword arguments.

Types:

  • *args: Used to pass a variable number of positional arguments. The arguments are received as a tuple.
    Example:
    def print_numbers(*numbers):
    for number in numbers:
    print(number) # Calling the function with variable number of arguments
    print_numbers(1, 2, 3, 4, 5)
    Explanation:
    **kwargs: Used to pass a variable number of keyword arguments. The arguments are received as a dictionary.
    Example:
def describe_person(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

# Calling the function with variable keyword arguments
describe_person(name="Alice", age=28, occupation="Engineer")

Explanation:
**kwargs collects all extra keyword arguments into a dictionary named kwargs.

5. Combination of Argument Types

Definition: You can combine positional arguments, keyword arguments, default arguments, and variable-length arguments in a function definition.

Example:

def complete_profile(name, age=30, *hobbies, **additional_info):
print(f"Name: {name}")
print(f"Age: {age}")
print("Hobbies:", hobbies)
for key, value in additional_info.items():
print(f"{key}: {value}")

# Calling the function with a combination of argument types
complete_profile("Bhanu", "Reading", "Traveling", city="Hyderabad", job="Engineer")

Explanation:

  • age is a default argument.
  • name is a positional argument.
  • *hobbies collects any number of positional arguments after the default argument.
  • **additional_info collects any number of keyword arguments.

Summary

  • Positional Arguments: Passed in the order of parameters.
  • Keyword Arguments: Passed with the parameter name, allowing any order.
  • Default Arguments: Parameters with default values.
  • Variable-Length Arguments: Use *args for variable positional arguments and **kwargs for variable keyword arguments.
  • Combination: You can mix and match these types in function definitions.

python Tuple

Python Tuple is a collection of objects separated by commas. In some ways, a tuple is similar to a Python list in terms of indexing, nested objects, and repetition but the main difference between both is Python tuple is immutable, unlike the Python list which is mutable.
Tuples are used to store multiple items in a single variable.
all with different qualities and usage.
A tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets().

Creating Tupple

You can create a tuple by enclosing the elements in parentheses () and separating them with commas.

# Example of creating a tuple
my_tuple = (1, 2, 3, "Bhanu", 4.5)

# A tuple can also be created without parentheses
another_tuple = 1, 2, 3

# Tuple with a single element
single_element_tuple = (5,)  # The comma is necessary

Typple as Return value

Tuples can be used as return values in Python functions to return multiple values from a function. This is useful when you want to return several related values at once without having to create a class or use global variables.

Example 1: Returning Multiple Values

Suppose you have a function that needs to return both the sum and product of two numbers. You can use a tuple to return both values:

def calculate_sum_and_product(x, y):
    sum_value = x + y
    product_value = x * y
    return sum_value, product_value  # Returns a tuple

# Using the function
result = calculate_sum_and_product(3, 5)

print(result)  # Output: (8, 15)

# Accessing individual elements
sum_result = result[0]
product_result = result[1]

print("Sum:", sum_result)       # Output: Sum: 8
print("Product:", product_result)  # Output: Product: 15

Advantages of Using Tuples as Return Values

  1. Simplicity: Tuples provide a simple way to group multiple return values without additional data structures.
  2. Readability: The code is cleaner and more readable, as the relationship between returned values is explicit.
  3. Immutability: Tuples ensure that the returned data remains unchanged, which can prevent accidental modifications.

When to Use Tuples

  • Use tuples when the returned data is logically grouped and should not be changed.
  • They are ideal for fixed-size collections where you know the number and types of elements beforehand.
  • When you want a quick way to return multiple values without the need for a custom data structure.

Operation of dictionaries/Assignment

Dictionaries in Python are powerful data structures that allow you to store and manipulate data in key-value pairs. They provide a flexible way to organize and access information, making them ideal for a wide range of programming tasks. Let’s explore the operations of dictionaries and how assignment works with them.

What is a Dictionary?

A dictionary is an unordered collection of items where each item is stored as a pair of keys and values. Dictionaries are mutable, meaning you can change, add, or remove items after the dictionary is created.

Key Characteristics of Dictionaries

  • Unordered: Dictionaries are unordered collections of data, meaning they do not maintain any order.
  • Key-Value Pairs: Each element is stored as a pair of keys and values.
  • Mutable: You can modify the contents of a dictionary by adding, updating, or removing items.
  • Unique Keys: Keys in a dictionary must be unique, but values can be duplicated.
  • Dynamic: You can add or remove items dynamically.
  • Creating a Dictionary

You can create a dictionary using curly braces {} with key-value pairs separated by a colon :. Here are some examples:

# Creating an empty dictionary
empty_dict = {}

# Creating a dictionary with initial values
person = {
    "name": "Bhanu",
    "age": 19,
    "location": "India"
}

print(person)  # Output: {'name': 'Bhanu', 'age': 19, 'location': 'India'}

Sets in python

In Python, sets are a collection type that is unordered, mutable, and does not allow duplicate elements. Sets are particularly useful when you want to eliminate duplicates from a list or perform common mathematical set operations like unions and intersections.
Set are represented by { } (values enclosed in curly braces)

Creating Sets

You can create a set by using the set() function or by using curly braces {}.

# Using set() function
my_set = set([1, 2, 3, 4])
print(my_set) # Output: {1, 2, 3, 4}

# Using curly braces
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}

Converting a list into set

The set() function in Python is used to create a set, which is an unordered collection of unique elements. When you convert a list into a set, set() removes any duplicate elements and provides a collection where each element appears only once.
Example:

# Original list with duplicates
list_with_duplicates = [10, 20, 10, 30, 40, 30]

# Converting the list to a set
unique_set = set(list_with_duplicates)

print(unique_set)  # Output: {10, 20, 30, 40}

In this example,
 the list list_with_duplicates contains duplicate elements. After conversion to a set, unique_set only contains the unique values from the original list.

Creating an empty set

To create an empty set in Python, you use the set() function with no arguments. Here’s how you can do it:
Example:

# Create an empty set
empty_set = set()

print(empty_set)  # Output: set()
Explanation:
This empty_set is an empty set object, ready to be populated with elements if needed. Note that you should not use curly braces {} to create an empty set, as {} is used for creating empty dictionaries in Python.
Data Structures

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top