- Blog Categories
- Software Development
- Data Science
- AI/ML
- Marketing
- General
- MBA
- Management
- Legal
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- Software Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Explore Skills
- Management Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
Python Cheat Sheet [2024]: A Must for Every Python Developer
Updated on 08 January, 2024
6.21K+ views
• 18 min read
Table of Contents
- What is Python?
- Operators in Python
- Control Statements in Python
- Loops
- Break and Continue Statements
- Pass Statements
- Function in Python
- Passing Keyword Arguments to a Function
- Collections in Python
- Dictionaries
- Tuple
- Set
- Types in Python
- Regular Expressions (Regex)
- Return Values and Return Statements in Python
- Exception Handling in Python
Anyone who follows computer programming languages knows that Python is moving forward at a tremendous pace. Back in June 2019, TIOBE noted that “if Python can keep this pace, it will probably replace C and Java in 3 to 4 years time, thus becoming the most popular programming language of the world.”
Fast forward to 2024 and Python is currently at the second position with a rating of 11.84%, and is well-positioned to surpass C to establish itself as the No. 1 programming language amongst developers!
What’s noteworthy is that Python’s ratings have significantly grown between this period — so much that it won the TIOBE programming language of 2020 award due to its rising popularity.
In this article, we deep-dive into Python and bring you a comprehensive Python syntax cheat sheet so you can brush up on important concepts of Python. It can work as a quick reference for both beginners and advanced developers.
So, let’s get started!
What is Python?
Python is a powerful, easy to learn, close-to-human language capable of delivering highly efficient and scalable applications. It is an open-source, high-level language offering a wide range of options for web development. Its real-world applications include artificial intelligence and machine learning, game development, scientific and numerical computation, web scraping, and more.
Python finds extensive use in data science and machine learning (ML). In 2020, its scikit-learn ML library witnessed an 11% growth in usage! However, that’s nothing compared to the 159% leap its PyTorch ML framework saw in the field of deep learning. As per the O’Reilly Data Science Salary Survey, nearly 54% of respondents stated that Python is their go-to tool for data science.
Since its launch in 1990 by Dutch programmer Guido van Rossum, Python has enjoyed the backing of developers worldwide and is favoured among junior developers as one of the easiest programming languages to learn. Python is often referred to as a scripting language that prioritizes code readability. It lays emphasis on the use of whitespace as compared to other programming languages that employ compact, tiny source files.
Among Python’s many popular products are Mozilla, Google, Cisco, NASA, and Instagram, among others. Not to mention, Python is a hugely popular extension for Microsoft’s Visual Studio Code.
Now, without further ado, let’s get started with our Python cheat sheet! We’ll begin with the basics.
Learn data science course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.
upGrad’s Exclusive Data Science Webinar for you –
ODE Thought Leadership Presentation
Operators in Python
1. Arithmetic Operators
There are seven maths operators in Python:
S.No
Maths Operators
Operation
Example
1
**
Exponent
2 ** 2 = 4
2
%
Modulus/Remainder
22 % 6 = 4
3
//
Integer division
22 // 8 = 2
4
/
Division
22 / 8 = 2.75
5
*
Multiplication
4 * 4 = 16
6
–
Subtraction
5 – 1 = 4
7
+
Addition
3 + 2 = 5
Here is a Python program using these operators:
x = 10
y =5
# Output: x + y = 15
print(‘x + y =’,x+y)
# Output: x – y = 5
print(‘x – y =’,x-y)
# Output: x * y = 50
print(‘x * y =’,x*y)
# Output: x / y = 2
print(‘x / y =’,x/y)
# Output: x // y = 2
print(‘x // y =’,x//y)
Output:
x + y = 15
x – y = 5
x * y = 50
x / y = 2
x // y =32
2. Logical Operators
There are three logical operators: and, or, not
- and: Returns True if both operands are true — x and y
- or: Returns True if any one of the operands is true — x or y
- not: It checks if the operand is false and returns True — not x
Here is a program showing how logical operators are used in Python:
x = True
y = False
print(‘The output of x and y is’,x and y)
print(‘The output of x or y is’,x or y)
print(‘The output of not x is’,not x)
Output
The output of x and y is False
The output of x or y is True
The output of not x is False
Explore our Popular Data Science Certifications
Our learners also read: Top Python Free Courses
3. Comparison Operators
Python has 6 comparison operators:
1. Equals: a == b
It checks whether the value on the left is equal to the value of the right.
2. Not Equals: a != b
It returns true if the value on the left is not equal to the value on the right.
3. Greater than: a > b
It returns true if the value on the left is greater than the value on the right.
4. Greater than or equal to: a >= b
It checks whether the value on the left is equal to the value on the right or greater than it.
5. Less than: a < b
If the value on the left is less than the value on the right, the condition becomes true.
6. Less than or equal to: a <= b
It returns true when the value on the left is equal to the value on the right or less than it.
Here is an example program:
x = 15
y = 12
z = 15
if ( x == z ):
print “Output 1: x is equal to z”
else:
print “Output 1: x is not equal to z”
if ( x != y ):
print “Output 2: x is not equal to y”
else:
print “Output 2: x is equal to y”
if ( x < y ):
print “Output 3: x is less than y”
else:
print “Output: x is not less than y”
if ( x > y ):
print “Output 4: x is greater than y”
else:
print “Output 4: x is not greater than y”
x = 15;
y = 30;
if ( a <= b ):
print “Output 5: x is less than or equal to y”
else:
print “Output 5: x neither less than nor equal to y”
if ( x >= y ):
print “Output 6: x is greater than or equal to y”
else:
print “Output 6: x is neither greater than nor equal to y”
The result of the above program will be−
Output 1: x is equal to z
Output 2: x is not equal to y
Output 3: x is not less than y
Output 4: x is greater than y
Output 5: x neither less than nor equal to y
Output 6: x is neither greater than nor equal to y
Check out all trending Python tutorial concepts in 2024.
Control Statements in Python
1. If Statements
Python’s logical statements can be used with conditional operators or if statements and loops to accomplish decision-making.
There are six conditional statements: If statement, if-else statement, nested if statement, If..elif ladder, short hand if statement, short hand if-else statement. These statements checked whether the given program is true or false.
2. If
These are used for simple conditions. Here is a short program for an if statement:
if 10 == 1:
print(“True!”)
Output:
True!
3. Nested If
Here is a short program for nested if statements used to perform complex operations:
x = 45
if x > 30:
print(“The result is above thirty,”)
if x > 35:
print(“and also above thirty five!”)
Output:
The result is above thirty
and also above thirty five!
We use indentation (or whitespace), an important functionality of Python used to separate blocks of code.
4. Elif Statements
elif keyword allows you to check more than another condition if the “if statement” was False. Here is a short program for an elif statement:
a = 99
b = 99
if b > a:
print(“b is greater than a”)
elif a == b:
print(“a and b are equal”)
Output:
a and b are equal
5. If Else Statements
If else statements allow adding more than one condition to a program. Take a look at this if-elif-else program:
if age < 5:
entry_charge = 0
elif age < 20:
entry_charge = 10
else: entry_charge = 20
6. If-Not-Statements
Not keyword lets you check for the opposite meaning to verify whether the value is NOT True:
new_list = [10, 20, 30, 40]
x = 50
if x not in new_list:
print(“‘x’ is not included on the list, so the condition is True!”)
Output:
‘x’ is not included on the list, so the condition is True!
Loops
Python has 2 kinds of loops: For loop and While loop.
1. For loop
It is used to execute the same sequence of statements n number of times. They are often used with lists.
# Program to find the sum of all numbers stored in a list
# List containing numbers
numbers = [6, 5, 3, 18, 4, 2, 15, 4, 11]
# variable to store the sum
sum = 0
# run iterations on the list
for val in numbers:
sum = sum+val
print(“The resultant sum is”, sum)
Output:
The resultant sum is 68
2. While loop
It is used to repeat a statement if a given condition is found to be true. It is also applicable to a sequence of statements. In the while loop, the condition is tested first, which is then followed by the execution.
# Program to compute the sum of natural numbers up to n
# sum = 1+2+3+…+n
# To get the value of n from the user,
n = int(input(“Enter the value of n: “))
# n = 5
# initialize sum and counter
sum = 0
i = 1
while i <= n:
sum = sum + i
i = i+1 # counter gets updated
# print the resultant sum
print(“The sum of the n naturals numbers is”, sum)
Output:
Enter the value of n: 5
The sum of the n naturals numbers is 15
Break and Continue Statements
In Python, Break and continue are used in the modification of the flow of a running loop. If a programmer wishes to end a current loop without checking whether the test expression is true or false, we use break and continue statements.
The break statement will immediately end the iteration running inside the loop it is included. In the case of a nested loop, the loop where the break is included is terminated.
Here is an example for a break statement:
# Use of break statement inside the loop
for val in “character”:
if val == “r”:
break
print(val)
print(“Program ends here”)
Output:
c
h
a
r
Program ends here
The continue statement skips the remaining code in the iteration and continues to the next.
Here’s a program to for a continue statement:
while True:
print(‘What is your name?’)
name = input()
if name != ‘Maria’:
continue
print(‘Hi Maria. Enter your password. (It is an apple.)’)
password = input()
if password == ‘pineapple’:
break
print(‘You’ve been granted access!’)
Pass Statements
A null statement is denoted as a pass statement in Python. As opposed to a comment, pass statements aren’t disregarded by Python. However, the execution of the statement still results in no operation (NOP).
Here’s an example for a pass statement:
”Time Is just a placeholder for
functionality that will be added later.”’
sequence = {‘t’, ‘i’, ‘m’, ‘e’}
for val in sequence:
pass
Function in Python
Functions are designated to perform a specific task. They comprise blocks of code that can be reused throughout the program as needed.
You can define your own function using the def keyword in Python. It is followed the name of the function and parentheses which take arguments: def name():
Here’s a short program to give you an idea:
def name():
print(“How are you doing?”)
name.py
def name():
print(“How are you doing?”)
name()
You can also add arguments to define the parameters of your function:
def subtract_numbers(x, y, z):
a = x – y
b = x – z
c = y – z
print(a, b, c)
subtract_numbers(6, 5, 4)
Output:
1
2
1
Passing Keyword Arguments to a Function
Functions also allow you to pass keywords as arguments. Here’s a simple Python code to do so:
# Define function with the following parameters
def item_info(item name, price):
print(“itemname: ” + item name)
print(“Price ” + str(dollars))
# Call the above function with assigned parameters
item_info(“Blue T-shirt”, 25 dollars)
# Call function using keyword arguments
item_info(itemname=”Trousers”, price=95)
Output:
Productname: Blue T-shirt
Price: 25
Productname: Trousers
Price: 95
Top Data Science Skills to Learn to upskill
SL. No | Top Data Science Skills to Learn | |
1 |
Data Analysis Online Courses | Inferential Statistics Online Courses |
2 |
Hypothesis Testing Online Courses | Logistic Regression Online Courses |
3 |
Linear Regression Courses | Linear Algebra for Analysis Online Courses |
Collections in Python
Python has four collection data types: List, Tuple, Set, and Dictionary.
1. Lists
Lists are data types that represent a sequence of elements in Python. It is one of the most commonly used data structures. They keep relevant data combined and allow you to perform common operations on different values simultaneously. Lists are mutable containers whereas strings are not.
Here is an example of lists:
first_list = [1, 2, 3]
second_list = [“a”, “b”, “c”]
third_list = [“4”, d, “book”, 5]
Lists can also be as functions:
master_list = list((“10”, “20”, “30”))
print(master_list)
2. Adding Items to a List
Here is a program for adding items to a list using append() function:
beta_list = [“eggs”, bacon”, “bread”]
beta_list.append(milk”)
print(beta_list)
Here is a program for adding items to a list using index() function:
beta_list = [“eggs”, bacon”, “bread”]
beta_list.insert(“2 mill”)
print(beta_list)
There are a number of actions you can perform on lists. These include adding items, removing items, combining items, creating nested lists, sorting, slicing, copying, etc.
3. List concatenation
Here’s a program to show list concatenation in Python:
>>> [X, Y, Z] + [‘A’, ‘B’, ‘C’]
[X, Y, Z, ‘A’, ‘B’, ‘C’]
>>> [‘L’, ‘M’, ‘N’] * 3
[‘L’, ‘M’, ‘N’ ‘L’, ‘M’, ‘N’ ‘L’, ‘M’, ‘N’]
>>> list_spam = [1, 2, 3]
>>> list_spam = list_spam + [‘A’, ‘B’, ‘C’]
>>> list_spam
[1, 2, 3, ‘A’, ‘B’, ‘C’]
4. Changing list values
Here’s a program to change list values using indexes:
>>> list_spam = [‘cat’, ‘dog’, ‘rat’]
>>> list_spam[1] = ‘gadjlnhs’
>>> list_spam
[‘cat’, ‘gadjlnhs’, ‘rat’]
>>> list_spam[2] = list_spam[1]
>>> list_spam
[‘cat’, ‘gadjlnhs’, ‘gadjlnhs’]
Lists find extensive use when working with data cleaning and for-loops. Here’s a Python syntax cheat sheet for using lists for different purposes:
Dictionaries
A Dictionary in Python is what enables element lookups. It is a commonly used data structure that leverages keys and values for indexing.
dict = {‘x’: 1, ‘y’: 2}
There are key-value pairs wherein every key has a value. This is a type of data structure that is extremely valuable for data scientists and finds use in web scraping.
Here’s an example for for using Dictionaries in Python:
thisdict = {
“brand”: “Skoda”,
“model”: “Octavia”,
“year”:”2017″
}
Tuple
If you need to store more than one item in a single variable, you can use Tuples. They are built-in data types that can be ordered or unchangeable.
Here’s an example:
thistuple = (“mango”, “papaya”, “blueberry”)
print(thistuple)
You can also add the same value twice or more times.
thistuple = (“mango”, “papaya”, “papaya”, “blueberry”)
print(thistuple)
Set
Set is another data type collection in Python that stores a sequence of elements in a single variable. They are also both ordered and unchangeable. The difference between sets and tuples is that sets are written using curly brackets whereas tuples are written using round brackets.
Another key differentiator is that sets do not accept duplicate elements.
this_set = (“mango”, 34, “papaya”, 40, “blueberry”)
print(this_set)
Here is an example for computing the difference of two sets:
X = {5, 6, 7, 8, 9}
Y = {8, 9, 10, 11, 12}
print(X-Y)
Output:
{5, 6, 7}
Here is an example for finding the interaction of two sets:
X = {5, 6, 7, 8, 9}
Y = {8, 9, 10, 11, 12}
print(A & B)
Output:
{8, 9}
Here’s listing a few methods that can be used with sets:
Method
Description
add()
To add one or more elements to a set
clear()
To clear the set of elements
copy()
To create a copy
difference()
It computes the difference of multiple sets and returns a new set
difference_update()
Every element from another set is removed from the current set
discard()
If an element is a member of the set, the function removes it. If it’s not, it does nothing
intersection()
It computes the intersection of two sets and returns the result in a new set
isdisjoint()
If there are no common elements in two sets, it turns True
issubset()
If another is a subset of the current set, it returns True
issuperset()
Returns True if this set contains another set
remove()
If the element is present in the set, it removes it. If not, a KeyError is raised
union()
It computes the union of sets and returns the result in a new set
Types in Python
Strings
Strings, as the name suggests, is a sequence of characters.
Some common methods used with respect to strings are lower(), upper(), lower(), replace(), count(), capitalize(), title().
String methods will return new values without modifying the original string. Anything that can be typed on the keyboard is a string — alphabet, number, special character.
In Python, strings are enclosed within single and double quotes, both of which represent the ends of a string.
Here is a Python strings cheat sheet:
Function
Description
str = str.strip()
To strip the string of all whitespace occurrences from either ends.
str = str.strip(‘chars’)
To strip all characters passed from either ends.
list = str.split()
To split any number of whitespaces.
str = str.join(coll_of_strings)
To join elements with a string acting as a separator.
bool = sub_str in str
To check whether or not a string contains a substring.
int = str.find(sub_str)
To return the initial index of the first match or return -1.
str = chr(int)
To convert the int value into a Unicode char.
int = ord(str)
To convert a unicode char into an int value
Regular Expressions (Regex)
A Regular Expression (RegEx) refers to a sequence of characters that points towards a search pattern in Python.
There’s a module in Python called re which is used with RegEx. Check out the example below:
import re
pattern = ‘*ma..er$’
test_str = ‘master’
result = re.match(pattern, test_str)
if result:
print(“The match was successful.”)
else:
print(“The match was unsuccessful.”)
Python has 14 metacharacters which are listed below:
\
Indicates a special meaning for the character that follows jt
[]
Character class
^
Matches with the beginning
$
Matches with the end
.
All characters except new line are matched
?
Matches zero. Also matches one occurrence
|
Represents OR. Any character separated by it is matched
*
Matches zero and any number of occurrences
{}
Points towards the number of occurrences that precede RE
()
Used to enclose more than one REs
Here is a Python RegEx cheat sheet for quick reference:
str = re.sub(regex, new, text, count=0)
Every occurrence is substituted with ‘new’.
list = re.findall(regex, text)
Every occurrence is converted into a string.
match = re.search(regex, text)
It goes through the regEx to look for the pattern’s first occurrence
match = re.match(regex, text)
Only the beginning of the text is searched
iter = re.finditer(regex, text)
All occurrences are returned as match objects.
Regex is commonly used by data scientists for data cleaning since it saves a lot of time.
Return Values and Return Statements in Python
When you define a function using def, Python allows you to specify the return value using a return statement. The statements include the return keyword along with the return value that the function is supposed to return.
Here’s an example:
import random
def findAnswer(answerNo):
if answerNo == 10:
return ‘It is accurate’
elif answerNo == 20:
return ‘It is not certain’
elif answerNo == 30:
return ‘Successful’
elif answerNo == 40:
return ‘Try again later’
elif answerNo == 50:
return ‘Unsuccessful. Try again later’
elif answerNo == 60:
return ‘Still unsuccessful. Try again later’
elif answerNo == 70:
return ‘The answer is no’
elif answerNo == 80:
return ‘The reply does not look so good’
elif answerNo == 90:
return ‘It is doubtful’
r = random.randint(1, 9)
fortune = findAnswer(r)
print(fortune)
Exception Handling in Python
An event or occurrence that disrupts the program flow or deviates from the program’s instructions is an exception. Python raises an exception if it encounters an event that it is not capable of dealing with. It essentially refers to an error:
Here’s a program to demonstrate exception handling in Python:
>>> while True:
… try:
… x = int(input(“Enter the number: “))
… break
… except ValueError:
… print(“Incorrect entry. Try again.”
This brings us to the end of our Python syntax cheat sheet. Given Python’s growing applications in data science, it is clear that the language will continue to dominate the industry for years to come. Its low learning curve and unmatched flexibility and scalability make it one of the best programming languages to learn today.
So if you’re interested in learning Python in-depth, join our Advanced Certificate Programme in Data Science now to build expertise in the domain and attract job opportunities from the top companies worldwide.
Read our popular Data Science Articles
Learn Python to Progress in the field of Data Science
Through the cutting-edge curriculum put together by upGrad and IIITB, students stand to gain industry-relevant skills and acquire knowledge of Statistics, Python Programming, Predictive Analytics using Python, Basic & Advanced SQL, Visualization using Python, EDA, and Basic & Advanced Machine Learning Algorithms.
The program also includes a complimentary Python programming Bootcamp for you to enhance your skills through hands-on industry projects. upGrad’s industry mentorship and peer to peer networking opportunities can land you high-paying jobs as a Data Scientist, ML Engineer, Data Analyst, Product Analyst, Business Analyst, or Chief Architect — depending on your field of interest.
So, don’t hesitate, kickstart your learning journey today! Let us know if you have any questions, we will be happy to help!
Frequently Asked Questions (FAQs)
1. Explain local and global variables in Python?
1. Local Variables: Variables that are defined or changed within a function are called local variables. The scope of these variables remains only within the function they are declared in and gets destroyed once the function ends.
2. Global Variables: Variables that are defined outside of a function or have a global scope are termed global variables. The scope of these variables remains throughout the program. The value of such a variable cannot be changed inside a function or else it will throw an error.
2. Which built-in data types are immutable in nature?
The immutable data types in Python include Number, Strings, and Tuple. The data stored in the variables of these types cannot be modified after declaration. The immutable nature makes the data more secure and provides ease to work with.
If you re-assign a new value to an immutable variable, then it allocates a separate space in the memory to store the new value. Hence, the original value of the immutable variable does get modified in any case.
3. Describe the major difference between list, tuple, set, and dictionary?
The following differentiates the Python collections based on the major parameters:
1. List -
a.The list is used to store ordered data
b. The data stored in a list can be mutated.
c. Lists can have duplicate elements.
2. Tuple -
a. A tuple is used to store ordered data.
b. The data stored in a tuple cannot be mutated.
c. Tuples can also contain duplicate elements.
3. Set -
a. Set is used to store unordered data.
b. Sets can be easily mutated.
c. A set can only contain unique data elements.
4. Dictionary
a. A dictionary is used to store unordered data.
b. The key-value pairs stored in a dictionary are mutable.
c. Dictionary elements should be unique as duplicates are not allowed.