Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Webscraping
  • Beautiful Soup
  • Request
  • Scrapy
  • open cv
  • Data analysis
  • Machine learning
  • NLP
  • Deep learning
  • Data Science
  • Interview question
  • ML math
  • ML Projects
  • ML interview
  • DL interview
Open In App
Next Article:
How to check horoscope using Python ?
Next article icon

Scrape LinkedIn Using Selenium And Beautiful Soup in Python

Last Updated : 01 Aug, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to scrape LinkedIn using Selenium and Beautiful Soup libraries in Python.

First of all, we need to install some libraries. Execute the following commands in the terminal.

pip install selenium  pip install beautifulsoup4

In order to use selenium, we also need a web driver. You can download the web driver of either Internet Explorer, Firefox, or Chrome. In this article, we will be using the Chrome web driver.

Note: While following along with this article, if you get an error, there are most likely 2 possible reasons for that.

  1. The webpage took too long to load (probably because of a slow internet connection). In this case, use time.sleep() function to provide extra time for the webpage to load. Specify the number of seconds to sleep as per your need.
  2. The HTML of the webpage has changed from the one when this article was written. If so, you will have to manually select the required webpage elements, instead of copying the element names written below. How to find the element names is explained below. Additionally, don’t decrease the window height and width from the default height and width. It also changes the HTML of the webpage.

Logging in to LinkedIn

Here we will write code for login into Linkedin, First, we need to initiate the web driver using selenium and send a get request to the URL and Identify the HTML document and find the input tags and button tags that accept username/email, password, and sign-in button.

LinkedIn Login Page

Code:

Python3

from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
 
# Creating a webdriver instance
driver = webdriver.Chrome("Enter-Location-Of-Your-Web-Driver")
# This instance will be used to log into LinkedIn
 
# Opening linkedIn's login page
driver.get("https://linkedin.com/uas/login")
 
# waiting for the page to load
time.sleep(5)
 
# entering username
username = driver.find_element(By.ID, "username")
 
# In case of an error, try changing the element
# tag used here.
 
# Enter Your Email Address
username.send_keys("User_email") 
 
# entering password
pword = driver.find_element(By.ID, "password")
# In case of an error, try changing the element
# tag used here.
 
# Enter Your Password
pword.send_keys("User_pass")       
 
# Clicking on the log in button
# Format (syntax) of writing XPath -->
# //tagname[@attribute='value']
driver.find_element(By.XPATH, "//button[@type='submit']").click()
# In case of an error, try changing the
# XPath used here.
                      
                       

After executing the above command, you will be logged into your LinkedIn profile. Here is what it would look like.

Part 1 Code Execution

Extracting Data From a LinkedIn Profile

Here is the video of the execution of the complete code.

Part 2 Code Execution

2.A) Opening a Profile and Scrolling to the Bottom

Let us say that you want to extract data from Kunal Shah’s LinkedIn profile. First of all, we need to open his profile using the URL of his profile. Then we have to scroll to the bottom of the web page so that the complete data gets loaded.

Python3

from selenium import webdriver
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
import time
 
# Creating an instance
driver = webdriver.Chrome("Enter-Location-Of-Your-Web-Driver")
 
# Logging into LinkedIn
driver.get("https://linkedin.com/uas/login")
time.sleep(5)
 
username = driver.find_element(By.ID, "username")
username.send_keys("")  # Enter Your Email Address
 
pword = driver.find_element(By.ID, "password")
pword.send_keys("")        # Enter Your Password
 
driver.find_element(By.XPATH, "//button[@type='submit']").click()
 
# Opening Kunal's Profile
# paste the URL of Kunal's profile here
profile_url = "https://www.linkedin.com/in/kunalshah1/"
 
driver.get(profile_url)        # this will open the link
                      
                       

Output:

Kunal Shah – LinkedIn Profile

Now, we need to scroll to the bottom. Here is the code to do that:

Python3

start = time.time()
 
# will be used in the while loop
initialScroll = 0
finalScroll = 1000
 
while True:
    driver.execute_script(f"window.scrollTo({initialScroll},
                                            {finalScroll})
                          ")
    # this command scrolls the window starting from
    # the pixel value stored in the initialScroll
    # variable to the pixel value stored at the
    # finalScroll variable
    initialScroll = finalScroll
    finalScroll += 1000
 
    # we will stop the script for 3 seconds so that
    # the data can load
    time.sleep(3)
    # You can change it as per your needs and internet speed
 
    end = time.time()
 
    # We will scroll for 20 seconds.
    # You can change it as per your needs and internet speed
    if round(end - start) > 20:
        break
                      
                       

The page is now scrolled to the bottom. As the page is completely loaded, we will scrape the data we want.

Extracting Data from the Profile

To extract data, firstly, store the source code of the web page in a variable. Then, use this source code to create a Beautiful Soup object.

Python3

src = driver.page_source
 
# Now using beautiful soup
soup = BeautifulSoup(src, 'lxml')
                      
                       

Extracting Profile Introduction:

To extract the profile introduction, i.e., the name, the company name, and the location, we need to find the source code of each element. First, we will find the source code of the div tag that contains the profile introduction.

Chrome – Inspect Elements

Now, we will use Beautiful Soup to import this div tag into python.

Python3

# Extracting the HTML of the complete introduction box
# that contains the name, company name, and the location
intro = soup.find('div', {'class': 'pv-text-details__left-panel'})
 
print(intro)
                      
                       

Output:

(Scribbled) Introduction HTML 

We now have the required HTML to extract the name, company name, and location. Let’s extract the information now:

Python3

# In case of an error, try changing the tags used here.
 
name_loc = intro.find("h1")
 
# Extracting the Name
name = name_loc.get_text().strip()
# strip() is used to remove any extra blank spaces
 
works_at_loc = intro.find("div", {'class': 'text-body-medium'})
 
# this gives us the HTML of the tag in which the Company Name is present
# Extracting the Company Name
works_at = works_at_loc.get_text().strip()
 
 
location_loc = intro.find_all("span", {'class': 'text-body-small'})
 
# Ectracting the Location
# The 2nd element in the location_loc variable has the location
location = location_loc[0].get_text().strip()
 
print("Name -->", name,
      "\nWorks At -->", works_at,
      "\nLocation -->", location)
                      
                       

Output:

Name --> Kunal Shah  Works At --> Founder : CRED  Location --> Bengaluru, Karnataka, India

Extracting Data from the Experience Section

Next, we will extract the Experience from the profile.

HTML of Experience Section

Python3

# Getting the HTML of the Experience section in the profile
experience = soup.find("section", {"id": "experience-section"}).find('ul')
 
print(experience)
                      
                       

Output:

Experience HTML Output

We have to go inside the HTML tags until we find our desired information. In the above image, we can see the HTML to extract the current job title and the name of the company. We now need to go inside each tag to extract the data

Scrape Job Title, company name and experience:

Python3

# In case of an error, try changing the tags used here.
 
li_tags = experience.find('div')
a_tags = li_tags.find("a")
job_title = a_tags.find("h3").get_text().strip()
 
print(job_title)
 
company_name = a_tags.find_all("p")[1].get_text().strip()
print(company_name)
 
joining_date = a_tags.find_all("h4")[0].find_all("span")[1].get_text().strip()
 
employment_duration = a_tags.find_all("h4")[1].find_all(
    "span")[1].get_text().strip()
 
print(joining_date + ", " + employment_duration)
                      
                       

Output:

'Founder' 'CRED' Apr 2018 – Present, 3 yrs 6 mos

Extracting Job Search Data

We will use selenium to open the jobs page.

Python3

jobs = driver.find_element(By.XPATH, "//a[@data-link-to='jobs']/span")
# In case of an error, try changing the XPath.
 
jobs.click()
                      
                       

Now that the jobs page is open, we will create a BeautifulSoup object to scrape the data.

Python3

job_src = driver.page_source
 
soup = BeautifulSoup(job_src, 'lxml')  
                      
                       

Scrape Job Title:

First of all, we will scrape the Job Titles.

HTML of Job Title

On skimming through the HTML of this page, we will find that each Job Title has the class name “job-card-list__title”. We will use this class name to extract the job titles.

Python3

jobs_html = soup.find_all('a', {'class': 'job-card-list__title'})
# In case of an error, try changing the XPath.
 
job_titles = []
 
for title in jobs_html:
    job_titles.append(title.text.strip())
 
print(job_titles)
                      
                       

 Output:

Job Titles List

Scrape Company Name:

Next, we will extract the Company Name.

HTML of Company Name

We will use the class name to extract the names of the companies:

Python3

company_name_html = soup.find_all(
  'div', {'class': 'job-card-container__company-name'})
company_names = []
 
for name in company_name_html:
    company_names.append(name.text.strip())
 
print(company_names)
                      
                       

Output:

Company Names List

Scrape Job Location:

Finally, we will extract the Job Location.

HTML of Job Location

Once again, we will use the class name to extract the location.

Python3

import re   # for removing the extra blank spaces
 
location_html = soup.find_all(
    'ul', {'class': 'job-card-container__metadata-wrapper'})
 
location_list = []
 
for loc in location_html:
    res = re.sub('\n\n +', ' ', loc.text.strip())
 
    location_list.append(res)
 
print(location_list)
                      
                       

Output:

Job Locations List



Next Article
How to check horoscope using Python ?

U

urvishmahajan
Improve
Article Tags :
  • Blogathon
  • Python
  • Selenium
  • Software Testing
  • Blogathon-2021
  • python
  • Python BeautifulSoup
  • Python bs4-Exercises
  • Python Selenium-Exercises
  • Python web-scraping-exercises
  • Python-selenium
Practice Tags :
  • python
  • python

Similar Reads

  • Python Exercise with Practice Questions and Solutions
    Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
    9 min read
  • Python List Exercise
    List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an
    3 min read
  • Python String Exercise
    Basic String ProgramsCheck whether the string is Symmetrical or PalindromeFind length of StringReverse words in a given StringRemove i’th character from stringAvoid Spaces in string lengthPrint even length words in a stringUppercase Half StringCapitalize the first and last character of each word in
    4 min read
  • Python Tuple Exercise
    Basic Tuple ProgramsPython program to Find the size of a TuplePython – Maximum and Minimum K elements in TupleCreate a list of tuples from given list having number and its cube in each tuplePython – Adding Tuple to List and vice – versaPython – Sum of tuple elementsPython – Modulo of tuple elementsP
    3 min read
  • Python Dictionary Exercise
    Basic Dictionary ProgramsPython | Sort Python Dictionaries by Key or ValueHandling missing keys in Python dictionariesPython dictionary with keys having multiple inputsPython program to find the sum of all items in a dictionaryPython program to find the size of a DictionaryWays to sort list of dicti
    3 min read
  • Python Set Exercise
    Basic Set ProgramsFind the size of a Set in PythonIterate over a set in PythonPython - Maximum and Minimum in a SetPython - Remove items from SetPython - Check if two lists have at-least one element commonPython program to find common elements in three lists using setsPython - Find missing and addit
    2 min read
  • Python Matrix Exercises

    • Python program to a Sort Matrix by index-value equality count
      Given a Matrix, the task is to write a Python program that can sort its rows or columns on a measure of the number of values equal to its index number. For each row or column, count occurrences of equality of index number with value. After computation of this count for each row or column, sort the m
      6 min read

    • Python Program to Reverse Every Kth row in a Matrix
      We are given a matrix (a list of lists) and an integer K. Our task is to reverse every Kth row in the matrix. For example: Input : a = [[5, 3, 2], [8, 6, 3], [3, 5, 2], [3, 6], [3, 7, 4], [2, 9]], K = 4 Output : [[5, 3, 2], [8, 6, 3], [3, 5, 2], [6, 3], [3, 7, 4], [2, 9]]Using reversed() and loopWe
      5 min read

    • Python Program to Convert String Matrix Representation to Matrix
      Given a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as
      4 min read

    • Python - Count the frequency of matrix row length
      Given a Matrix, the task is to write a Python program to get the count frequency of its rows lengths. Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]] Output : {3: 2, 2: 2, 1: 1} Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present. Input :
      5 min read

    • Python - Convert Integer Matrix to String Matrix
      Given a matrix with integer values, convert each element to String. Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]] Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] Explanation : All elements of Matrix converted to Strings. Input : test_list = [[4, 5, 7], [10, 8, 3]] Output : [
      6 min read

    • Python Program to Convert Tuple Matrix to Tuple List
      Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
      8 min read

    • Python - Group Elements in Matrix
      Given a Matrix with two columns, group 2nd column elements on basis of 1st column. Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] Output : {5: [8, 4], 2: [0, 3, 9]} Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2
      6 min read

    • Python - Assigning Subsequent Rows to Matrix first row elements
      Given a (N + 1) * N Matrix, assign each column of 1st row of matrix, the subsequent row of Matrix. Input : test_list = [[5, 8, 10], [2, 0, 9], [5, 4, 2], [2, 3, 9]] Output : {5: [2, 0, 9], 8: [5, 4, 2], 10: [2, 3, 9]} Explanation : 5 paired with 2nd row, 8 with 3rd and 10 with 4th Input : test_list
      3 min read

    • Adding and Subtracting Matrices in Python
      In this article, we will discuss how to add and subtract elements of the matrix in Python. Example: Suppose we have two matrices A and B. A = [[1,2],[3,4]] B = [[4,5],[6,7]] then we get A+B = [[5,7],[9,11]] A-B = [[-3,-3],[-3,-3]] Now let us try to implement this using Python 1. Adding elements of t
      4 min read

    • Python - Convert Matrix to Dictionary
      The task of converting a matrix to a dictionary in Python involves transforming a 2D list or matrix into a dictionary, where each key represents a row number and the corresponding value is the row itself. For example, given a matrix li = [[5, 6, 7], [8, 3, 2], [8, 2, 1]], the goal is to convert it i
      4 min read

    • Python - Convert Matrix to Custom Tuple Matrix
      Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used
      6 min read

    • Python - Matrix Row subset
      Sometimes, while working with Python Matrix, one can have a problem in which, one needs to extract all the rows that are a possible subset of any row of other Matrix. This kind of problem can have applications in data domains as a matrix is a key data type in those domains. Let's discuss certain way
      7 min read

    • Python - Group similar elements into Matrix
      Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
      8 min read

    • Python - Row-wise element Addition in Tuple Matrix
      Sometimes, while working with Python tuples, we can have a problem in which we need to perform Row-wise custom elements addition in Tuple matrix. This kind of problem can have application in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[('Gfg', 3
      4 min read

    • Create an n x n square matrix, where all the sub-matrix have the sum of opposite corner elements as even
      Given an integer N. The task is to generate a square matrix of ( n x n ) having the elements ranging from 1 to n^2 with the following condition: The elements of the matrix should be distinct i.e used only onceNumbers ranging from 1 to n^2Every sub-matrix you choose should have the sum of opposite co
      6 min read

    Python Functions Exercises

    • Python splitfields() Method
      The splitfields() method is a user-defined method written in Python that splits any kind of data into a list of fields using a delimiter. The delimiter can be specified as an argument to the method, and if no delimiter is specified, the method splits the string using whitespace characters as the del
      3 min read

    • How to get list of parameters name from a function in Python?
      The task of getting a list of parameter names from a function in Python involves extracting the function's arguments using different techniques. These methods allow retrieving parameter names efficiently, whether from bytecode, introspection or source code analysis. For example, if a function fun(a,
      4 min read

    • How to Print Multiple Arguments in Python?
      An argument is a value that is passed within a function when it is called. They are independent items or variables that contain data or codes. At the time of function call each argument is always assigned to the parameter in the function definition. Example: [GFGTABS] Python def GFG(name, num): prin
      4 min read

    • Python program to find the power of a number using recursion
      Given a number N and power P, the task is to find the power of a number ( i.e. NP ) using recursion. Examples: Input: N = 2 , P = 3Output: 8 Input: N = 5 , P = 2Output: 25 Approach: Below is the idea to solve the above problem: The idea is to calculate power of a number 'N' is to multiply that numbe
      3 min read

    • Sorting Objects of User Defined Class in Python
      Sorting objects of a user-defined class in Python involves arranging instances of the class based on the values of one or more of their attributes. For example, if we have a class Person with attributes like name and age, we might want to sort a list of Person objects based on the age attribute to o
      5 min read

    • Assign Function to a Variable in Python
      In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
      4 min read

    • Returning a function from a function - Python
      In Python, functions are first-class objects, allowing them to be assigned to variables, passed as arguments and returned from other functions. This enables higher-order functions, closures and dynamic behavior. Example: [GFGTABS] Python def fun1(name): def fun2(): return f"Hello, {name}!"
      5 min read

    • What are the allowed characters in Python function names?
      The user-defined names that are given to Functions or variables are known as Identifiers. It helps in differentiating one entity from another and also serves as a definition of the use of that entity sometimes. As in every programming language, there are some restrictions/ limitations for Identifier
      2 min read

    • Defining a Python Function at Runtime
      One amazing feature of Python is that it lets us create functions while our program is running, instead of just defining them beforehand. This makes our code more flexible and easier to manage. It’s especially useful for things like metaprogramming, event-driven systems and running code dynamically
      3 min read

    • Explicitly define datatype in a Python function
      Unlike other programming languages such as Java and C++, Python is a strongly, dynamically-typed language. This means that we do not have to explicitly specify the data type of function arguments or return values. Python associates types with values rather than variable names. However, if we want to
      4 min read

    • Functions that Accept Variable Length Key Value Pair as Arguments
      To pass a variable-length key-value pair as an argument to a function, Python provides a feature called **kwargs.kwargs stands for Keyword arguments. It proves to be an efficient solution when one wants to deal with named arguments (arguments passed with a specific name (key) along with their value)
      3 min read

    • How to find the number of arguments in a Python function?
      Finding the number of arguments in a Python function means checking how many inputs a function takes. For example, in def my_function(a, b, c=10): pass, the total number of arguments is 3. Some methods also count special arguments like *args and **kwargs, while others only count fixed ones. Using in
      4 min read

    • How to check if a Python variable exists?
      Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a va
      4 min read

    • Get Function Signature - Python
      A function signature in Python defines the name of the function, its parameters, their data types , default values and the return type. It acts as a blueprint for the function, showing how it should be called and what values it requires. A good understanding of function signatures helps in writing c
      3 min read

    • Python program to convert any base to decimal by using int() method
      Given a number and its base, the task is to convert the given number into its corresponding decimal number. The base of number can be anything like digits between 0 to 9 and A to Z. Where the value of A is 10, value of B is 11, value of C is 12 and so on. Examples: Input : '1011' base = 2 Output : 1
      2 min read

    Python Lambda Exercises

    • Python - Lambda Function to Check if value is in a List
      Given a list, the task is to write a Python program to check if the value exists in the list or not using the lambda function. Example: Input : L = [1, 2, 3, 4, 5] element = 4 Output : Element is Present in the list Input : L = [1, 2, 3, 4, 5] element = 8 Output : Element is NOT Present in the list
      2 min read

    • Difference between Normal def defined function and Lambda
      In this article, we will discuss the difference between normal 'def' defined function and 'lambda' function in Python. Def keyword​​​​​​​In Python, functions defined using def keyword are commonly used due to their simplicity. Unlike lambda functions, which always return a value, def functions do no
      2 min read

    • Python: Iterating With Python Lambda
      In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the exp
      2 min read

    • How to use if, else & elif in Python Lambda Functions
      Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else & elif in Lambda Functions. Using if-else in lambda functionThe lam
      2 min read

    • Python - Lambda function to find the smaller value between two elements
      The lambda function is an anonymous function. It can have any number of arguments but it can only have one expression. Syntax lambda arguments : expression In this article, we will learn how to find the smaller value between two elements using the Lambda function. Example: Input : 2 5 Output : 2 Inp
      2 min read

    • Lambda with if but without else in Python
      In Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value. Since a lambda function must have a return value for every valid input, we
      3 min read

    • Python Lambda with underscore as an argument
      In Python, we use the lambda keyword to declare an anonymous function. Lambda function behaves in the same way as regular functions behave that are declared using the 'def' keyword. The following are some of the characteristics of Python lambda functions: A lambda function can take more than one num
      1 min read

    • List comprehension and Lambda Function in Python
      List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A var
      3 min read

    • Nested Lambda Function in Python
      Prerequisites: Python lambda In Python, anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. When we use lambda function inside another lambda function then
      2 min read

    • Python lambda
      In Python, an anonymous function means that a function is without a name. As we already know that def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions. Python lambda Syntax:lambda arguments : expressionPython lambda Example:[GFGTABS] Python
      4 min read

    • Python | Sorting string using order defined by another string
      Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat =
      2 min read

    • Python | Find fibonacci series upto n using lambda
      The Fibonacci numbers are the numbers in the following integer sequence. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ........ In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1. Find the series of fi
      2 min read

    • Overuse of lambda expressions in Python
      What are lambda expressions? A lambda expression is a special syntax to create functions without names. These functions are called lambda functions. These lambda functions can have any number of arguments but only one expression along with an implicit return statement. Lambda expressions return func
      8 min read

    • Python Program to Count Even and Odd Numbers in a List
      In Python working with lists is a common task and one of the frequent operations is counting how many even and odd numbers are present in a given list. The collections.Counter method is the most efficient for large datasets, followed by the filter() and lambda approach for clean and compact code. Us
      4 min read

    • Intersection of two Arrays in Python ( Lambda expression and filter function )
      Finding the intersection of two arrays using a lambda expression and the filter() function means filtering elements from one array that exist in the other. The lambda defines the condition (x in array2), and filter() applies it to the first array to extract common elements. For example, consider two
      1 min read

    Python Pattern printing Exercises

    • Simple Diamond Pattern in Python
      Given an integer n, the task is to write a python program to print diamond using loops and mathematical formulations. The minimum value of n should be greater than 4. Examples : For size = 5 * * * * * * * * * * * * For size = 8 * * * * * * * * * * * * * * * * * * * * * * * * * * For size = 11 * * *
      3 min read

    • Python - Print Heart Pattern
      Given an even integer input, the task is to write a Python program to print a heart using loops and mathematical formulations. Example :For n = 8 * * * * * * * * * * G F G * * * * * * * * For n = 14 * * * * * * * * * * * * * * * * * * G F G * * * * * * * * * * * * * * Approach : The following steps
      3 min read

    • Python program to display half diamond pattern of numbers with star border
      Given a number n, the task is to write a Python program to print a half-diamond pattern of numbers with a star border. Examples: Input: n = 5 Output: * *1* *121* *12321* *1234321* *123454321* *1234321* *12321* *121* *1* * Input: n = 3 Output: * *1* *121* *12321* *121* *1* * Approach: Two for loops w
      2 min read

    • Python program to print Pascal's Triangle
      Pascal's triangle is a pattern of the triangle which is based on nCr, below is the pictorial representation of Pascal's triangle. Example: Input: N = 5Output: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1Method 1: Using nCr formula i.e. n!/(n-r)!r! After using nCr formula, the pictorial representation becomes: 0C0
      3 min read

    • Python program to print the Inverted heart pattern
      Let us see how to print an inverted heart pattern in Python. Example: Input: 11 Output: * *** ***** ******* ********* *********** ************* *************** ***************** ******************* ********************* ********* ******** ******* ****** ***** **** Input: 15 Output: * *** ***** *****
      2 min read

    • Python Program to print hollow half diamond hash pattern
      Give an integer N and the task is to print hollow half diamond pattern. Examples: Input : 6 Output : # # # # # # # # # # # # # # # # # # # # Input : 7 Output : # # # # # # # # # # # # # # # # # # # # # # # # Approach: The idea is to break the pattern into two parts: Upper part: For the upper half st
      4 min read

    • Program to Print K using Alphabets
      Given a number n, the task is to print 'K' using alphabets.Examples: Input: n = 5 Output: A B C D E F A B C D E A B C D A B C A B A A A B A B C A B C D A B C D E A B C D E F Input: n = 3 Output: A B C D A B C A B A A A B A B C A B C D Below is the implementation. C/C++ Code // C++ Program to design
      5 min read

    • Program to print half Diamond star pattern
      Given an integer N, the task is to print half-diamond-star pattern. ************************************ Examples: Input: N = 3 Output: * ** *** ** * Input: N = 6 Output: * ** *** **** ***** ****** ***** **** *** ** * Approach: The idea is to break the pattern into two halves that is upper half and
      4 min read

    • Program to print window pattern
      Print the pattern in which there is a hollow square and plus sign inside it. The pattern will be as per the n i.e. number of rows given as shown in the example. Examples: Input : 6 Output : * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Input : 7 Output : * * * * * * * * * * * * * *
      7 min read

    • Python Program to print a number diamond of any given size N in Rangoli Style
      Given an integer N, the task is to print a number diamond of size N in rangoli style where N means till Nth number from number ‘1’. Examples: Input : 2 Output : --2-- 2-1-2 --2-- Input : 3 Output : ----3---- --3-2-3-- 3-2-1-2-3 --3-2-3-- ----3---- Input : 4 Output : ------4------ ----4-3-4---- --4-3
      3 min read

    • Python program to right rotate n-numbers by 1
      Given a number n. The task is to print n-integers n-times (starting from 1) and right rotate the integers by after each iteration.Examples: Input: 6 Output : 1 2 3 4 5 6 2 3 4 5 6 1 3 4 5 6 1 2 4 5 6 1 2 3 5 6 1 2 3 4 6 1 2 3 4 5 Input : 3 Output : 1 2 3 2 3 1 3 1 2 Method 1: Below is the implementa
      2 min read

    • Python Program to print digit pattern
      The program must accept an integer N as the input. The program must print the desired pattern as shown in the example input/ output. Examples: Input : 41325 Output : |**** |* |*** |** |***** Explanation: for a given integer print the number of *'s that are equivalent to each digit in the integer. He
      3 min read

    • Print with your own font using Python !!
      Programming's core function is printing text, but have you ever wished to give it a unique look by utilizing your own custom fonts? Python enables you to use imagination and overcome the standard fonts in your text outputs. In this article, we will do some cool Python tricks. For the user input, the
      4 min read

    • Python | Print an Inverted Star Pattern
      An inverted star pattern involves printing a series of lines, each consisting of stars (*) that are arranged in a decreasing order. Here we are going to print inverted star patterns of desired sizes in Python Examples: 1) Below is the inverted star pattern of size n=5 (Because there are 5 horizontal
      2 min read

    • Program to print the Diamond Shape
      Given a number n, write a program to print a diamond shape with 2n rows. Examples : [GFGTABS] C++ // C++ program to print diamond shape // with 2n rows #include <bits/stdc++.h> using namespace std; // Prints diamond pattern with 2n rows void printDiamond(int n) { int space = n - 1; // run loop
      11 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences