Your ultimate guide

All functions in List, Tuple, Set and Dict from Python

Most commonly used functions in List(mutable) and Tuple(immutable):
Lists and tuples are similar, but lists are mutable while tuples are immutable. 
Function [List] (Tuple)
len(list/Tuple): Returns the number of elements in the list/Tuple Y Y
append(item): Adds an item to the end of the list. Y N
extend(iterable): Appends the elements of an iterable (e.g., another list) to the end of the list. Y N
insert(index, item): Inserts an item at a specific index. Y N
remove(item): Removes the first occurrence of a specific item. Y N
pop(index): Removes and returns the item at a specific index. If no index is provided, it removes and returns the last item. Y N
index(item): Returns the index of the first occurrence of the specified item. Y Y
count(item): Returns the number of times a specific item appears in the list/tuple. Y Y
sort(): Sorts the list in ascending order. Y N
sort(reverse=True): Sorts the list in descending order. Y N
reverse(): Reverses the order of elements in the --list. Y N
copy(): Returns a shallow copy of the list. Y N
clear(): Removes all items from the list. Y N
min(list/tuple)`: Returns the minimum value in the list/tuple. Y Y
max(list/tuple): Returns the maximum value in the list/tuple. Y Y
sum(list/tuple): Returns the sum of all elements in the list/tuple. Y Y
sorted(iterable): Returns a new sorted list from the elements of an iterable without modifying the original list/tuple. Y Y
any(iterable): Returns True if any element in the iterable is True. Y Y
all(iterable): Returns True if all elements in the iterable are True. Y Y
zip(iterable1, iterable2): Combines two or more iterables into tuples, stopping when the shortest iterable is exhausted. Y Y
enumerate(iterable): Returns an iterator that yields pairs of index and value for each element in the iterable. Y Y
filter(function, iterable): Returns an iterator containing only the elements of the iterable for which the function returns `True`. Y Y



🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴



Most commonly used functions in Set(Mutable) and Frozenset(Immutable):
  • set(iterable): Create a new set from an iterable.
  • frozenset(iterable_name): Create a new frozenset from an iterable(list, set, tuple).
Function {set} (frozenset)
add(element): Adds an element to the set. Y N
update(iterable): Updates the set by adding elements from an iterable. Y N
remove(element): Removes an element from the set. Raises an error if the element is not present. Y N
discard(element): Removes an element from the set if it exists; does not raise an error if the element is not present. Y N
pop(): Removes a random element from the set. Raises an error if the set is empty. Y N
clear()`: Removes all elements from the set. Y N
copy(): Returns a shallow copy of the set/frozenset. Y Y
difference(other): Returns a new set containing elements that are in the current set/frozen but not in the other set/frozenset.
Syntax(x and y are set's): z = x.difference(y)
Y Y
difference_update(other): Removes the elements that exist in both sets from the original set.
Syntax(x and y are set's): x.difference_update(y)
Y N
intersection(other): Returns a new set/frozenset containing elements that are in both the current set/frozenset and the other set/frozenset.
Syntax: z = x.intersection(y)
Y Y
intersection_update(other): Updates the set by keeping only elements that are also in the other set
Syntax: x.intersection_update(y)
Y N
union(other): Returns a new set/frozenset containing all unique elements from both the current set/frozenset and the other set/frozenset.
Syntax: z = x.union(y)
Y Y
update(other): Updates the set by adding elements from another set.
Syntax: x.update(y)
Y N
issubset(other): Returns `True` if the set/frozenset is a subset of the other set/frozenset. Y Y
issuperset(other): Returns `True` if the set/frozenset is a superset of the other set/frozenset. Y Y
isdisjoint(other): Returns `True` if the set/frozenset has no elements in common with the other set/frozenset. Y Y



🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴🛴



The most commonly used functions in the Dictionary(dicts):
Function
### Creating Dictionaries:
dict(): Creates an empty dictionary.
dict(key=value, ...): Creates a dictionary with key-value pairs.
dict(iterable): Creates a dictionary from an iterable of key-value pairs (e.g., a list of tuples).

### Accessing and Modifying Elements:
d[key]: Accesses the value associated with a specific key. Raises a `KeyError` if the key is not present.
d.get(key): Accesses the value associated with a key. Returns `None` if the key is not present (no error).
d.get(key, default): Accesses the value associated with a key, returning the specified default value if the key is not present.
d.keys(): Returns a view of all keys in the dictionary.
d.values(): Returns a view of all values in the dictionary.
d.items(): Returns a view of key-value pairs in the dictionary.
d.pop(key): Removes and returns the value associated with a specific key. Raises a `KeyError` if the key is not present.
d.pop(key, default): Removes and returns the value associated with a key, returning the specified default value if the key is not present.
d.popitem(): Removes and returns an arbitrary key-value pair as a tuple.
d.update(other_dict): Updates the dictionary with key-value pairs from another dictionary.
d.setdefault(key, default): Returns the value associated with a key, or sets it to the default value if the key is not present.

### Dictionary Views:
dict.keys(): Returns a view of keys in the dictionary.
dict.values(): Returns a view of values in the dictionary.
dict.items(): Returns a view of key-value pairs in the dictionary.

### Dictionary Methods:
d.clear(): Removes all key-value pairs from the dictionary.
d.copy(): Returns a shallow copy of the dictionary.
d.fromkeys(iterable, value): Creates a new dictionary with keys from an iterable and values set to a specified value.
d.setdefault(key, default): Returns the value associated with a key, or sets it to the default value if the key is not present.
d.update(other_dict): Updates the dictionary with key-value pairs from another dictionary.

### Other Functions:
len(d): Returns the number of key-value pairs in the dictionary.
sorted(d): Returns a sorted list of keys in the dictionary.
in and not in operators: Check if a key exists in the dictionary.
Git-Bash Setup & Git Commands

Git-Bash Setup & Git Commands



Git Bash:
    Git Bash is a command-line interface and shell environment that allows users to interact with Git, which is a version control system used for tracking changes in source code during software development. 
    Git Bash is one of the tools developers can use to interact with GitHub repositories through Git Command.




Git Bash installation:
  • Download the Git Bash setup based on your Operating System from the official website: "https://git-scm.com/downloads"
  • Run the .exe file you downloaded and follow the instructions in the installer.
  • Run Git Bash by right-clicking on any folder and selecting the Git Bash Here option from the context menu(right-click menu) or Search for the Git Bash app on the Start menu, then open it. 




Git Bash Setup:
Step 1: Setup User Name and Email ID
When we open Git Bash for the first time we should set up a user name and email ID details in Git Bash. For that enter the following command.

git config --global user.name "FIRST_NAME LAST_NAME"

Example:
git config --global user.name "Testing Colleges"
The user name does not need to same as your GitHub account user name.

After running the command if you want to change the user name then run the same command again it will replace the existing name.

git config --global user.email "YOUR_EMAIL"

Example:
git config --global user.email "email@example.com"
Provide only your email ID associated with your GitHub account.

To check the configuration details enter the following command:
git config --global –list

Step 2: Create a  Git Local Repository
    A Git local repository is a local copy of a Git repository. It is stored in a directory on your computer and contains all of the files and directories that are being tracked by Git. The Git local repository is used to manage changes to your code, such as adding new files, deleting files, and editing files. It is also used to track the history of changes to your code.
    By using the git init command we can create a new Git repository in Git Bash. This would create a new .git directory in the current directory, which would contain all of the necessary Git metadata for the new repository.

Here is an example of how you could use Git Bash to create a new Git repository.
Open Git Bash and Navigate to the directory where you want to create the Git repository, to navigate to the specific directory we will use the "cd" command (where "cd" stands for "change directory")
cd [absoult path of a directory]

Example:
cd E:\PythonPrograms
Type the following command:
git init

Once we create a git repository it will create three logical areas:
  1. Working Area/Untracked Files
  2. Staging Area/Tracked Files
  3. Local Repository
Working Area/Untracked Files:
  1. Whatever files are created in the git repository are automatically stored in this Working area
  2. For example, we are creating a file “DBConnect.py” by using the “touch DBConnect.py” command.
  3. To know the status of the file, and in which area the file is located use the “git status” command, if the file is in Red color then that file is in the Working Area.
Staging Area/Tracked Files
    After the file is completed in the working Area we are going to send that file into Staging Area. For that, we will use the following commands:
  1. git add .  : To send all files from the working area to the staging area.
  2. git add [filename1] [filename2]: To send specific files from the working area to the staging area. 
    • E.g.: git add DBConnect.py Index.sh
  3. git add *.<extension>: To send specific extension files from the working area to the staging area.
    • E.g.: git add *.py
    To know the status of the files, and in which area it is located use the “git status” command, if the files are in Green colour then those files are in the Staging Area.

Local Repository
    To commit the files to the Staging Area to the Local repository we will use the following commands.
  1. git commit –m “message”: To send all files from the Staging area to the Local repository. Eg: #git commit –m “First commit”
  2. git commit –m “message” [filename1] [filename2]: To send a specific file/s from the Staging area to the Local repository. E.g.: git commit -m "python files" DBConnect.py
    To know the status of the file, and in which area it is located use the “git status” command, if there are no files and displays “nothing to commit, working tree clean” then those files are in the Local repository area.


Step 3: Mapping Remote Repository to Local Repository
  • To connect GitHub to the Local repository, Go to your repository in your GitHub account.
  • Then select the "Code" option and copy the "HTTPS" URL


  • Now open the Git Bash application, and enter the following command to map the remote repository to the local repository.
git remote add [alias name] [https:// URL]
Here alias name is any local name that is used to refer to a remote repository.

Example:
git remote add tcp https://github.com/TestingColleges/python.git

To check which URL is mapped the command is ”git remote –v”


Step 4: Push the files from the Local Repository to the Remote Repository:
  • Go to git bash and enter the following command
git push [alias name] [branch name]

Example:
git push tcp master
  • Here master/main is a default branch name.
  • When you execute the command mentioned above, it will prompt you to enter your GitHub login details.
    • Enter the username of your GitHub account.
    • To access certain features, we require the use of a Personal Access Token (PAT) ID instead of a traditional password.
    • To obtain a PAT, navigate to GitHub, click on your profile, select Settings, then navigate to Developer settings and click on Personal access token. Finally, click on Generate new token.
    • Provide the token name, select its expiry date and select access scopes for personal tokens.
    • Then click on Generate Token
    • Now we get the PAT token, Copy the token & save it somewhere, because later won’t not able to see it again.
    • Past the PAT token in Password and hit the Enter key. Then it will push the files from the Local repository to the Remote repository.
  • The Next time, it will not be going to ask for the credentials, these credentials are stored in the Credential Manager application in Windows, and Keychain Access in Mac if you want you can delete these Credentials there



So Git Flow is: git init → git status → git add → git commit → git remote add → git push

Git and GitHub:
  • Git is a Version Control System, that is used to develop the codes and main the versioning.
  • GitHub is a Hosting service, that can be used to manage the source code, it will provide the GUI.
Difference between Git and SVN:
    Git is a Distributed Version Control System (DVCS). In this first we work on a Local repository then we distribute the code into a Remote Repository.
    SVN, CVS, and TFS are only Version Control Systems (VCS). In this, we will directly work on the Remote Repository.

Git + SVN = No
SVN client + SVN = Yes
Git + GitHub = Yes
Git + GitLab = Yes
Git + BitBucket = Yes
Git + Azure repos = Yes

What is a Version Control System?
    Developers make constant changes to code while creating an application, even after the official release. Version control systems help keep track of these changes by storing them in a central repository. This makes it easy for developers to collaborate on a project by downloading and uploading new revisions. By doing so, they can share the latest version of software with other developers, who can then make changes and contribute.


Note: After committing, if you modify the file code in the Local repository, then that modified file is stored in the working area.

We can send the modified file directly into the Local repository using the following command:
git commit -a -m “message”
Only this command works for modified files

git log: It will give all commit ids with detailed information.
git log -2: It will display the last 2 commit ids.
git log --oneline: It will give all commit ids without detailed information

git show [commit ID]: It will give details of this commit ID (we can get the commit ID in the “git log” command). E.g.: git show abc12345
git show --pretty="" --name-only  [Commit ID]: It will display all the files that are committed in that particular commit. E.g.: git show --pretty="" --name-only abc12345

To remove the working area file:
git clean -n: It will preview the changes that we are going to remove.
git clean -f: If we want to remove new files from the working area (Deleted data cannot be recovered).

To get back the file from the Staging area to the Working area:
git reset: To revert back all files to working from the staging area.
git reset [File Name]: To revert back the specific file to working from the staging area.

git revert [Commit ID]: It will revert the changes committed in that particular commit ID from the local repo.
git push origin master -f: It will revert the changes from the remote repo.
About GitHub & Setup

About GitHub & Setup


GitHub:
    GitHub is a web-based code hosting platform for software development and version control using Git. Git is a distributed version control system that helps developers manage and track changes in their code during the development process.
    GitHub allows developers to store their code repositories, collaborate with other team members or contributors, and manage projects efficiently. It provides features such as issue tracking, pull requests, code review, wikis, and actions for continuous integration and deployment.

    Similarly, like GitHub, there are other Source code Management(SVM) Tools are there like GitLab, Bit Bucket Server, SVN(Apache Sub Version), CVS(Concurrent Version System), TFS(Team Foundation Server), and so on.
* In Azure they have their own Source Code Management Tool Called Azure Repos.

Here are some key features and functionalities of GitHub:
  1. Repository: A repository (repo) is a storage space where a project's code and related files are stored. It's a central place for collaboration and version control.
  2. Version Control: GitHub uses Git for version control, enabling developers to track changes to their code, work on different branches, merge changes, and roll back to previous versions if needed.
  3. Collaboration: GitHub allows multiple developers to work on the same project simultaneously. Developers can create branches to work on specific features or fixes and merge them back into the main branch (often called "master" or "main").
  4. Issues and Pull Requests: Users can report issues or bugs in a repository, and developers can address them by creating pull requests with proposed code changes. Pull requests allow for code review and discussion before merging changes into the main branch.
  5. Code Review: GitHub facilitates collaborative code review, enabling team members to review proposed changes, comment on code, suggest improvements, and approve or request further modifications.
  6. Actions: GitHub Actions automates software development workflows, including build, test, and deployment processes. Users can create custom workflows or use pre-defined Actions to streamline their development workflow.
  7. Wikis and Documentation: GitHub provides a wiki feature for creating and maintaining project documentation, which is useful for explaining project structure, processes, or usage.
  8. Community and Social Interaction: GitHub has a strong community of developers who contribute to open-source projects, share code, collaborate, and discuss various topics related to software development.




GitHub Setup
Steps to Setup GitHub:
  1. To begin, the first thing you should do is create a GitHub account.
  2. Afterwards, you can create an organization within your account.
  3. After setting up the organization, you can then create a repository for your project.
  4. Once the repository is created, you can create teams within your organization.
  5. As needed, you can add members to each team.
  6. Lastly, you should grant the appropriate team access to the repository so they can contribute to your project.

Step 1: Create a GitHub account
  • Go to GitHub's official website. https://github.com
  • Click on the Sign up button.
  • Then on the next page give your personal details:
    • Email Id:
    • Create Password:
    • Enter a username:
    • Verify your account : (Please solve the simple puzzle to verify that you are human)
    • Then Click on the Create account Button.
  • Verify the email by entering the code: You'll receive an email with a code(or OTP) from GitHub. Enter that code on this verification page, then click Continue.
  • GitHub displays a quick survey, you can also skip this survey by clicking Skip personalization.
  • On the plan selection page, choose the free plan.

Step 2: Create Organization
    Within the organization, we can create repositories.
  • To create an Organization, first, you need to log in to your GitHub Account.
  • Then on the top right corner, we will see the "+" symbol, Click on that one.
  • Then select New Organization.

  • Then we will see three different plans (1. Free, 2. Team, 3. Enterprise)


  • Click on Free (Create a free Organization)
  • On the Next page, Setup your organization details:
    • Organization Account name* : <Give your organization name>
    • Contact email*: <Enter your email id>
    • This organization belong to: <Select "My personal account">
    • Verify your account by solving the simple puzzle.
    • Click on Next.
    • Then Click on Complete Setup.

Step 3: Create a Repository
   A repository is a location where we store all the source code and revise each file history.
  • In your GitHub account, in the top right corner, we will see the "+" symbol, Click on that one.
  • Select New repository.



  • Fill in all the details.
    • Owner*: < Select your Organization in Dropdown >
    • Repository name*: < Give the repository Name >
    • Description (optional): < Optional >
    • Select one option either Public or Private
      • Public < Selecting this option for Anyone on the internet can see this repository. You choose who can commit. >
      • Private < Select this option for You choose who can see and commit to the repository >


    • Initialize this repository with: < Don't select any option >
    • Click on the Create repository button.
    • Like this, we can create any number of repositories in a single organization.

Step 4: Create a Team
    A Team is a group of individuals (GitHub users) brought together within an organization to collaborate on repositories and projects more effectively. Teams help in organizing members, controlling access, and managing permissions within an organisation.
  • Open your Organization(click on your profile, then click on Your Organizations, Select your Organizations).
  • Then click on the Teams option.
  • Then Click on New team.


  • Fill in all details:
    • Team name: < Give the name of your team >
    • Description: < Optional  >
    • Team visibility: Select one option. The Team can be visible or secret
      • Visible: < Visible teams can be viewed and @mentioned  by every organization member.>
      • Secret: < Secret teams are only visible to the people on the team and people with owner permissions.>
    • Then click on Create team.

Step 5: Add Users to the Team
  • Open your Organization and click on 👥Teams.
  • Then click on your Team.
  • Then Select the Members option and Select the Add a member button.
  • Invite the Users by username, full name, or email address

  • After Creating a team we can also give the individual role to the users like Maintainer, Member
    • Maintainer: Can add and remove team members and create child teams.
    • Member: Has no administrative permissions on the team.

Step 6: Provide Repository Access to team
  • Open your team, then Click on Repositories.
  • Then click on the Add repository button, and type your repository name that we going to access to the team.



  • Then click on Add repository to team

  • After Providing repository access to the team, we can give the Permission level to access the repository by default it will be Read permission. If you want we can change the permission level.
    • Permission Level:
      • Read: Can read and clone this repository. Can also open and comment on issues and pull requests.
      • Triage: Can read and clone this repository. Can also manage issues and pull requests.
      • Write: Can read, clone. and push to this repository. Can also manage issues and pull requests.
      • Maintain: Can read, clone and push to this repository. They can also manage issues, pull requests, and some repository settings.
      • Admin: Can read, clone, and push to this repository. Can also manage issues, pull requests, and repository settings, including adding collaborators.



  • Just click on the permission you want it will apply to that team.

Fix Browser Closes Automatically - Immediately after test without Calling Quit and Close()

To resolve issues with automatically closing browsers while using Selenium in Python, it is necessary to properly configure the Chrome WebDriver:

To configure Chrome WebDriver pre-requirements:
  1. Before running the script, make sure you have the required Python packages installed. You can install them using pip if you haven't already:
    • pip install selenium webdriver-manager
  2. These commands will install the 'selenium' package for Selenium WebDriver and the 'webdriver-manager' package for managing WebDriver executables like ChromDriver automatically.
  3. To install packages using pip within PyCharm, you can follow these steps:
    1. Open PyCharm: Launch Pycharm and open your Python project or create a new one.
    2. Open a Terminal: In PyCharm, you can access a terminal by clicking on "View" in the menu bar and selecting "Tool Windows" and then "Terminal".
    3. Run the pip Command: In the terminal, run the following command.
      • pip install webdriver-manager
    4. Wait for Installation: Pip will download and install the package and its dependencies.



Here's how you can fix this issue:
  1. Import the necessary modules
    • from selenium.webdriver.chrome.service import Service
    • from webdriver_manager.chrome import ChromeDriverManager
  2. Creates an instance of the 'ChromeOptions' class, which allows you to configure various options and preferences for the Chrome WebDriver.
    • options = webdriver.ChromeOptions()
  3. Add an experimental option to the 'ChromeOptions' object and pass the "detach" option, set to True, which allows the WebDriver to detach from the browser session after the WebDriver script has finished executing. This means that the browser window will remain open even after your script has completed its tasks.
    • options.add_experimental_option("detach", True)
  4. Create a WebDriver instance for Chrome with the specified options. It uses the ChromeDriverManager to automatically download and manage the Chrome WebDriver executable (chromedriver.exe) and set it up for use with Selenium. 
    • driver = webdriver.Chrome(options = options, service = Service(ChromeDirverManager().install()))
  5. With this configuration, you can now use the 'driver' object to interact with the Chrome browser, and the browser window will remain open even after your Selenium script has been completed.
  6. If you call the quit or close() function, then the browser will close.



Example Programs:
  1. from selenium import webdriver
  2. from selenium.webdriver.common.by import By

  3. from selenium.webdriver.chrome.service import Service
  4. from webdriver_manager.chrome import ChromeDriverManager

  5. options = webdriver.ChromeOptions()
  6. options.add_experimental_option("detach", True)
  7. driver = webdriver.Chrome(options=options, service=Service(ChromeDriverManager().install()))

  8. driver.get("https://example.com")


Handling Drop Down using Selenium with Python

Select Class:
  • If we want to work on the drop-down first we need to create object an instance of the 'Select' Class.
    • Syntax: object = Select(dropdown_element)
    • Example:
      1. dropdown = driver.find_element(By.ID, 'tcg')
      2. obj = Select(dropdown)
    • Example 2:
      1. obj = Select(driver.find_element(By.ID, 'tcg'))
  • Select class interacts with dropdown elements in web pages.
  • Select Class contain different functions by using that function we can handle the dropdown elements.
    • Select Class functions are:
    1. options 
      • Returns a list of all options to this select tag
    2. all_selected_options(self) 
      • Return a list of all selected options to this select tag
    3. first_selected_option(self) 
      • The first selected option in this select tag
    4. select_by_value(self, value: str)
      • Select all options that have a value matching the argument.
    5. select_by_index(self, index: int)
      • Select the option at the given index.
    6. select_by_visible_text(self, text: str)
      • Select all options that display text matching the argument.
    7. deselect_all(self)
      • Clear all selected entries. This is only valid when the SELECT supports multiple selections.
    8. deselect_by_value(self, value:str)
      • Deselect all options that have a value matching the argument.
    9. deselect_by_index(self, value: int)
      • Deselect the option at the given index.
    10. deselect_by_visible_text(self, text:str)
      • Deselect all options that display text matching the argument.
Note: The Select Class functions are designed specifically for dropdowns on a web page created using the select tag.



Let's explore each function in a Select class in detail. Refer to the image below for the source code and output of a dropdown.





options:
    options function allows you to retrieve all the available options within a dropdown element.

Here's how you can use the option method in the Select class:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element on the page.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'options' function to retrieve all the available options as a list of 'WebElement' objects:
    • all_options = select.options
  6. Now, all_options will contain a list of WebElement objects, each representing an option within the dropdown.
  7. You can then perform various operations on these options, such as selecting an option, getting the text or value of an option, etc.
  8. For example, to print the text of all options:
    • for option in all_options:
    •     print(option.text)



all_selected_options:
    This function is used to retrieve all the selected options from a multi-select dropdown or list on a web page.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the multi-select dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'all_selected_options' function to retrieve all the selected options as a list of 'WebElement' objects:
    • selected_options = select.all_selected_options
  6. Now, selected_options will contain a list of WebElement objects.
  7. You can then perform various operations on these options, such as unselecting the option, getting the text or value of an option, etc.
  8. For example, to print the text of all selected options:
    • for option in selected_options:
    •     print(option.text)



first_selected_option:
    The 'fist_selected_option' function is used to retrieve the first selected option from a dropdown or list. 

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'first_selected_option' function to retrieve the first selected option as a WebElement object:
    • first_option = select.first_selected_option
  6. You can then access the text or other attributes of the first selected option:
    • print(first_option.text)



select_by_value('option_value'):
    The 'select_by_value' method is used to select an element by specifying its 'value' attribute in the dropdown.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'select_by_value' function to select an option by specifying its 'value' attribute:
    • select.select_by_value('option_value')
deselect_by_value:
    This function is exactly the opposite of the 'select_by_value' function. This is used to deselect an element by specifying its 'value' attribute in the dropdown.
    So in the above example instead of giving 'select_by_value' if you give 'deselect_by_value' then that option will be deselected from the multi-select dropdown.



select_by_index:
    The 'select_by_index' method is used to select an option in the dropdown by specifying its index. The index is a zero-based integer that represents the position of the option in the dropdown list.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg') //replace with the actual ID of your dropdown element.
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Use the 'select_by_index' method to select an option by specifying its index.
    • select.select_by_index(3)
  6. Then use the 'select_by_index(3)' function will select the fourth option(since the index is zero-based) in the dropdown.
Similarly, we have the 'deselect_by_index' function to deselect an option by specifying its index.



select_by_visible_text:
    The 'select_by_visible_text' function is used to select an option from a dropdown by specifying its visible text (the text that is displayed to the user).

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the dropdown.
    • select = Select(dropdown)
  5. Then use the 'select_by_visible_text' function to select an option by specifying its visible text:
    • select.select_by_visible_text('option_text')
  6. Then it will select the option with the text "option_text" in the dropdown.

Similarly, we have a function to deselect the option in the dropdown by using visible text that is 'deselect_by_visible_text'.



deselect_all:
    The 'deselect_all' function is used to deselect all selected options in a multi-select dropdown.

Here's how you can use it:
  1. Import the necessary modules:
    • from selenium import webdriver
    • from selenium.webdriver.support.select import Select
  2. Instantiate a WebDriver instance (e.g., ChromeDriver) and navigate to a web page:
    • driver = webdriver.Chrome()
    • driver.get("https://example.com")
  3. Locate the dropdown element you want to interact with.
    • dropdown = driver.find_element(By.ID, 'tcg')
  4. Create a 'Select' object and use it to interact with the multi-select dropdown.
    • select = Select(dropdown)
  5. Then use the 'deselect_all' function to deselect all selected options in the dropdown:
    • select.deselect_all()
  6. After calling 'select.deselect_all()', all previously selected options in the multi-select dropdown will be deselected.