Wednesday, September 4, 2024

PYTHON - DICTIONARY

 Dictionary


A Python dictionary is a data structure that stores key-value pairs. It's similar to a real-world dictionary where you look up a word (the key) to find its definition (the value). Here are some essential functions and operations associated with Python dictionaries:

1. Creating a Dictionary: You can create a dictionary using curly braces `{}` and separating key-value pairs with colons.
For example:
   python
   my_dict = {"key1": value1, "key2": value2}

Dict1 = {"Name":"Bhaskar","Desg":"Domain Lead","Age":34,"City":"Chennai"}
print(Dict1)

my_dict2 = dict(name="Bob", age=25, city="Los Angeles")
print(my_dict2)
   

2. Accessing Values: You can access the value associated with a specific key using square brackets [].
For example:
   python
   value = my_dict["key1"]


EID424 = {"Name":"Bhaskar","Desg":"Domain Lead","City":"Chennai"}
EID425 = {"Name":"Senthil","Desg":"Domain Mem","City":"Chennai"}
EID426 = {"Name":"Venkatesh","Desg":"Domain Manager","City":"Chennai"}
print(EID426)
desg = EID426["Desg"]
print(desg)

for item in EID424.values():
    print(item)

for key in E424.keys(): # iterate through keys
    print(key)
   
for value in E424.values():  # iterate through values
    print(value)
   
for key,value in E424.items():  # iterate through keys value pairs
    print(key,value)  

3. Adding or Updating Key-Value Pairs: You can add new key-value pairs or update existing ones by assigning a value to a new or existing key. For example:
   python
   my_dict["new_key"] = new_value
   

4. Removing Key-Value Pairs: You can remove key-value pairs using the del keyword or the `pop()` method. For example:
   python
   del my_dict["key1"]
   value = my_dict.pop("key2")
   

5. Dictionary Methods:
   - keys(): Returns a view object that displays a list of all the keys in the dictionary.
   - values(): Returns a view object that displays a list of all the values in the dictionary.
   - items(): Returns a view object that displays a list of key-value tuples.
   - get(key): Returns the value associated with the specified key. If the key does not exist, it returns `None` (or a default value if provided).
   - clear(): Removes all key-value pairs from the dictionary.

6. Checking Key Existence: You can check if a key exists in a dictionary using the `in` keyword. For example:
   python
   if "key1" in my_dict:
       # do something
 

7. Dictionary Comprehension: Like list comprehensions, Python supports dictionary comprehensions for creating dictionaries in a compact and efficient manner. For example:
   python
   squares = {x: x*x for x in range(1, 6)}
   

These are just some of the fundamental operations and methods associated with Python dictionaries

PYTHON - SETS

 Sets:


Sets are unordered collections of unique elements.
They are defined using curly braces {} or the set() constructor.
Sets are useful for removing duplicates and performing set operations (union, intersection, difference, etc.).

In Python, a set is an unordered collection of unique elements. Sets are defined using curly braces {} or the set() constructor. Sets do not allow duplicate values, and they are primarily used for performing mathematical set operations like union, intersection, difference, and more. Here, I'll explain in detail about sets and their operations in Python.

Example:

my_set = {1, 2, 3, 4, 4}

1. Creating Sets:
You can create a set by enclosing a sequence of elements within curly braces {} or by using the set() constructor. Sets can contain elements of any data type.

my_set1 = {1, 2, 3, 4, 5}
my_set2 = set([3, 4, 5, 6, 7])

2. Adding Elements:
You can add elements to a set using the add() method. Sets do not allow duplicate values, so adding a duplicate will have no effect.

my_set = {1, 2, 3}
my_set.add(4)  # Adds 4 to the set
my_set.add(2)  # Does not add 2 (already in the set)

3. Removing Elements:
You can remove elements from a set using the remove() or discard() method. The remove() method raises a KeyError if the element does not exist, while discard() does nothing in such cases.

my_set = {1, 2, 3, 4}
my_set.remove(3)   # Removes 3 from the set
my_set.discard(2)  # Removes 2 from the set

4. Set Operations:

Sets support various set operations like union, intersection, difference, and symmetric difference.

Union (| or union()): Combines two sets, keeping only unique elements.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2  # or set1.union(set2)
Intersection (& or intersection()): Returns elements that are common to both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2  # or set1.intersection(set2)
Difference (- or difference()): Returns elements in the first set but not in the second.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
difference_set = set1 - set2  # or set1.difference(set2)
Symmetric Difference (^ or symmetric_difference()): Returns elements that are in either of the sets but not in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
symmetric_diff_set = set1 ^ set2  # or set1.symmetric_difference(set2)

5. Checking Membership:
You can check if an element is a member of a set using the in keyword.

my_set = {1, 2, 3}
is_present = 2 in my_set  # Returns True

6. Length of a Set:
You can find the number of elements in a set using the len() function.

my_set = {1, 2, 3, 4}
length = len(my_set)  # Returns 4

7. Iterating Through Sets:
You can use a for loop to iterate through the elements of a set.

my_set = {1, 2, 3}
for item in my_set:
    print(item)

Sets are commonly used for tasks that require unique values or for performing set-related operations like checking for common elements between collections, finding unique elements, or eliminating duplicates. Sets are an essential part of Python's standard library for data manipulation.

Common operations on sets inclu
de:

Adding elements: add()
Removing elements: remove(), discard()
Set operations: union(), intersection(), difference(), symmetric_difference()
Finding length: len()
Iterating: for item in my_set

 

PYTHON - TUPLES

 Tuples:


Tuples are similar to lists but are immutable (cannot be modified once created).
They are defined using parentheses ().
Tuples are often used for data that should not change during the program's execution.

In Python, a tuple is an ordered, immutable (unchangeable), and iterable collection of elements. Tuples are similar to lists but have the key difference that once you create a tuple, you cannot modify its elements. Tuples are defined using parentheses (), and elements within the tuple are separated by commas. Here, I'll explain in detail about tuples and their operations in Python.

Example:

my_tuple = (1, 2, 3, "Python", 5.0)

1. Creating Tuples:
You can create a tuple by enclosing a sequence of values or objects within parentheses. Tuples can contain elements of any data type, including numbers, strings, other tuples, or a combination of types.

my_tuple = (1, 2, 3, "Python", 5.0)

2. Accessing Elements:
You can access individual elements in a tuple by their index, just like with lists. Python uses zero-based indexing.

first_element = my_tuple[0]  # Accesses the first element (1)
third_element = my_tuple[2]  # Accesses the third element (3)

3. Immutability:
Tuples are immutable, which means you cannot change their elements after they are created. Attempting to modify a tuple will result in an error.

my_tuple[3] = "Hello"  # This will raise a TypeError


4. Tuple Packing and Unpacking:
You can pack multiple values into a single tuple or unpack a tuple into individual variables.

# Packing values into a tuple
my_packed_tuple = 1, "Python", 3.14
print(my_packed_tuple)

# Unpacking a tuple into variables
x, y, z = my_packed_tuple

5. Finding Elements:
You can use the index() method to find the index of the first occurrence of a specific value in the tuple. If the element is not found, it raises a ValueError.

index_of_2 = my_tuple.index(2)  # Finds the index of the element 2 (1)

6. Length of a Tuple:
You can find the number of elements in a tuple using the len() function.

length = len(my_tuple)  # Returns the length of the tuple (5)

7. Iterating Through Tuples:

You can use a for loop to iterate through the elements of a tuple.

for item in my_tuple:
    print(item)

8. Concatenating Tuples:
You can concatenate two or more tuples using the + operator to create a new tuple.

tuple1 = (1, 2, 3)
tuple2 = ("a", "b", "c")
concatenated_tuple = tuple1 + tuple2

9. Repetition:
You can create a new tuple by repeating an existing tuple using the * operator.

my_tuple = (1, 2)
repeated_tuple = my_tuple * 3  # Creates (1, 2, 1, 2, 1, 2)

Tuples are commonly used when you need to represent a collection of elements that should not be modified, such as coordinates, record fields, or function return values. The immutability of tuples can help ensure data integrity in your programs.

Common operations on tuples include:

Accessing elements: indexing
Unpacking: (a, b) = (1, 2)
Finding length: len()
Iterating: for item in my_tuple

Python -Lists

 Lists:


Lists are one of the most versatile and commonly used data structures in Python.
They are ordered, mutable (modifiable), and can contain elements of different data types.
Lists are defined using square brackets [].

Example:

my_list = [1, 2, 3, "Python", 5.0]

Common operations on lists include:

Adding elements: append(), insert()
Removing elements: remove(), pop()
Accessing elements: indexing and slicing
Modifying elements: direct assignment
Finding length: len()
Iterating: for item in my_list

In Python, a list is a fundamental data structure that allows you to store and manipulate collections of data. Lists are ordered, mutable (modifiable), and can contain elements of different data types. Lists are defined using square brackets [], and elements within the list are separated by commas. Here, I'll explain in detail about lists and their operations in Python.

1. Creating Lists:
You can create a list by enclosing a sequence of values or objects within square brackets. Lists can contain elements of any data type, including numbers, strings, other lists, or even a combination of types.

my_list = [1, 2, 3, "Python", 5.0]

2. Accessing Elements:
You can access individual elements in a list by their index. Python uses zero-based indexing, meaning the first element has an index of 0, the second has an index of 1, and so on.

first_element = my_list[0]  # Accesses the first element (1)
third_element = my_list[2]  # Accesses the third element (3)

3. Modifying Elements:
Lists are mutable, which means you can change their elements by assigning new values to specific indices.

my_list[3] = "Hello"  # Modifies the fourth element

4.Adding Elements:

You can add elements to the end of a list using the append() method, or insert elements at a specific index using the insert() method.

   

my_list.append(6)        # Adds 6 to the end of the list
my_list.insert(1, "A")   # Inserts "A" at index 1


        5. Removing Elements:


You can remove elements from a list by their value using the remove() method, or by their index using the pop() method. The pop() method also returns the removed element.


my_list.remove("Python")  # Removes "Python" from the list
removed_element = my_list.pop(2)  # Removes the third element (3)

6. Slicing Lists:
Slicing allows you to create sublists by specifying a range of indices. The syntax for slicing is list[start:end], where start is the inclusive index and end is the exclusive index.

sublist = my_list[1:4]  # Creates a sublist from index 1 to 3 ([2, "Hello", 6])

7. Finding Elements:
You can use the index() method to find the index of the first occurrence of a specific value in the list. If the element is not found, it raises a ValueError.

index_of_2 = my_list.index(2)  # Finds the index of the element 2 (1)

8. Length of a List:
You can find the number of elements in a list using the len() function.

length = len(my_list)  # Returns the length of the list (4)

9. Iterating Through Lists:
You can use a for loop to iterate through the elements of a list.

for item in my_list:
    print(item)

These are some of the basic operations you can perform on lists in Python. Lists are versatile and widely used in Python for tasks such as data storage, iteration, and manipulation. Understanding how to work with lists is essential for many programming tasks.

BASICS PYTHON PROGRAMMING (Arrays and Strings)

 Arrays Using Lists:


In Python, you can create arrays using lists. Lists are dynamic arrays that can hold elements of different data types.

# Creating an array using a list
my_array = [1, 2, 3, 4, 5]

# Accessing elements in the array
print(my_array[0])  # Output: 1

You can perform various operations on lists, such as appending, extending, and slicing:

# Appending an element to the end of the array
my_array.append(6)

# Extending the array with another list
my_array.extend([7, 8, 9])

# Slicing the array to get a subset
subset = my_array[2:5]  # [3, 4, 5]


Strings:

Strings are sequences of characters and are immutable.
They are defined using single quotes '' or double quotes "".
Example:

my_string = "strings are a fundamental data type"


In Python, strings are a fundamental data type, and the language provides a wide range of built-in string methods to manipulate and work with strings effectively.

str.capitalize():

This method returns a copy of the string with its first character capitalized and the rest of the characters in lowercase

text = "strings are a fundamental data type"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: "Hello world"

str.upper() and str.lower():

str.upper() converts all characters in a string to uppercase.
str.lower() converts all characters in a string to lowercase.

text = "Hello World"
upper_text = text.upper()
lower_text = text.lower()
print(upper_text)  # Output: "HELLO WORLD"
print(lower_text)  # Output: "hello world"

str.strip([chars]):

This method returns a copy of the string with leading and trailing characters (specified in the optional chars parameter) removed.

text = "   Hello, World!   "
stripped_text = text.strip()  # Removes leading/trailing spaces
print(stripped_text)  # Output: "Hello, World!"


str.replace(old, new[, count]):

This method replaces all occurrences of the old substring with the new substring in the string. You can also specify the count parameter to limit the number of replacements.

Example:

text = "Hello, World, World"
new_text = text.replace("World", "Python")
print(new_text)  # Output: "Hello, Python, Python"

str.split([sep[, maxsplit]]):

This method splits the string into a list of substrings based on the specified separator (sep). You can also specify the maximum number of splits with the maxsplit parameter.

text = "apple,banana,orange"
fruits = text.split(",")
print(fruits)  # Output: ['apple', 'banana', 'orange']

You can split a sentence into words using the split() function in Python. By default, split() separates the string at whitespace characters (spaces, tabs, and newline characters). You can also specify a custom separator if needed. Here's how you can use the split() function:

# Splitting a sentence into words using the default separator (whitespace)
sentence = "This is a sample sentence."
words = sentence.split()

# Printing the list of words
print(words)

In the example above, the split() function splits the sentence string into a list of words using whitespace as the separator.

If you want to split a sentence using a custom separator (e.g., comma or hyphen), you can pass that separator as an argument to the split() function:

# Splitting a sentence using a custom separator (e.g., comma)
sentence = "Apples,bananas,oranges"
words = sentence.split(',')

# Printing the list of words
print(words)

In this case, we used a comma as the separator to split the sentence into words.

Remember that the split() function returns a list of words, and you can then manipulate or iterate through this list as needed for your specific task

str.join(iterable):

This method concatenates elements from an iterable (e.g., a list or tuple) using the string as a separator.
Example:

fruits = ['apple', 'banana', 'orange']
joined_text = ', '.join(fruits)
print(joined_text)  # Output: "apple, banana, orange"

str.startswith(prefix[, start[, end]]) and str.endswith(suffix[, start[, end]]):

These methods check whether a string starts or ends with the specified prefix or suffix, respectively. The optional start and end parameters can be used to specify the range of characters to check.
Example:

text = "Hello, World"
starts_with_hello = text.startswith("Hello")
ends_with_world = text.endswith("World")
print(starts_with_hello)  # Output: True
print(ends_with_world)    # Output: True

These are some of the most commonly used string methods in Python. String methods make it easy to perform a wide range of operations on strings, from simple transformations to more complex manipulations. You can combine these methods to achieve more sophisticated string processing tasks.

Common string operations include:

Concatenation: +
Slicing: my_string[0:5]
Length: len(my_string)
String methods: split(), strip(), upper(), lower(), replace(), etc.