0% found this document useful (0 votes)
62 views

Copyprogramming Com Howto Must Have Python Cheat Sheets

This document provides a cheat sheet for various Python topics including data types, strings, conditionals, lists, dictionaries, functions, date/time handling, exceptions, OOP concepts, and module imports. It also includes summaries of essential Python reference sheets focused on regular expressions, NumPy/Pandas, web scraping, Django, and Flask. The cheat sheet aims to be a helpful quick reference for common Python concepts and tasks.

Uploaded by

Harry Harry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Copyprogramming Com Howto Must Have Python Cheat Sheets

This document provides a cheat sheet for various Python topics including data types, strings, conditionals, lists, dictionaries, functions, date/time handling, exceptions, OOP concepts, and module imports. It also includes summaries of essential Python reference sheets focused on regular expressions, NumPy/Pandas, web scraping, Django, and Flask. The cheat sheet aims to be a helpful quick reference for common Python concepts and tasks.

Uploaded by

Harry Harry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

CopyProgramming Home PHP AI Front-End Mobile Database Programming languages CSS NodeJS Cheat sheet

Python

Essential Python Reference Sheets Hetzner offer


Signs up and receive €30 in cloud credits with
Hetzner, the best cloud hosting service in 2022.
Author: Theresa Allen Date: 2023-04-13 Register new account and receive 30 Euro free
credit lifetime (Available for new customers
only). This promotion is available for a limited
This cheat sheet covers various Python topics including naming conventions, data types, type
time, so act fast before it’s too late!
conversion, strings, common functions, conditionals, iterations, lists, tuples, dictionaries, functions,
date and time, file handling, catching exceptions, OOP, module import, and basic operations. It also
includes information on basic data types such as integers, floats, strings, complex numbers, and
booleans. Additionally, it covers taking user input with the input() function. The cheat sheet is still a
work in progress and credits go to EricTheCoder_. There is also information on if statements, elif
statements, else statements, loops, while loops, for loops, creating and calling functions, passing
arguments, lambda functions, and more.

Search

Search

Search

Related questions
What is regex cheat sheet in Python?
Python Programming, like any other
How to make Tabs Design Using HTML & CSS - @codingpakistan @CodeWit… Programming Language, makes use of Regex
or Regular Expressions which play a
Table of contents
significant role in searching for and replacing
Must-Have Python Cheat Sheets specified text patterns. These patterns are
formed by a group of characters in the
Ultimate Python Cheat Sheet
regular expression and are commonly
Python Cheat Sheet for Beginners referred to as reg-ex patterns.

What is regex cheat sheet in Python? How to create a Reddit bot in Python?
To set up a Reddit bot, we'll be utilizing the
How to create a Reddit bot in Python?
Python Reddit API Wrapper (PRAW), which
What is Reddit and how does it work? permits us to access the website's backend
by logging into the Reddit API. You can
Where does the password of the Reddit account go?
acquire more details about this tool by
referring to it as PRAW - Python Reddit API
Must-Have Python Cheat Sheets Wrapper.

In recent years, Python has gained popularity as a programming language. With the assistance of What is Reddit and how does it work?
various useful tools, tasks ranging from data manipulation to web development can be performed Reddit comprises various interest-based
communities known as subreddits. Users
quickly and efficiently. Among these tools, cheat sheets is particularly useful for providing quick
have the option to subscribe to multiple
references for string manipulations and regular expressions . To begin using this language, check out
subreddits to engage in posting, commenting,
a blog post that recommends ten essential Python cheat sheets . and interacting with them.
Here are ten must-have Python cheat sheets to get you started with the language!
Where does the password of the Reddit
account go?
Python Regular expressions cheat sheet provides a comprehensive set of tools for manipulating The password for the Reddit account will be
strings and utilizing regular expressions in Python, making it an invaluable resource for anyone entered into the password field, while the
user_agent serves as a distinct marker used
needing to perform these functions. It encompasses a wide range of regex operations that are by Reddit to identify the origin of network
commonly used. requests. For accessing Reddit's API as a
script application, both client_id and
client_secret are required.
For those who are new to Python and working with data, this cheat sheet is an excellent resource.
Within it, you will find demonstrations of how to utilize libraries such as NumPy, Pandas, Matplotlib,
and Seaborn. Latest posts
A Python Tutorial: Utilizing the list index()
For those who want to scrape web pages using Python, this cheat sheet is an excellent resource. It Method Explained with Example
contains a range of suggestions for web scraping, including techniques and tools like Selenium,
A comprehensive tutorial on implementing
making it an ideal starting point.
the readline() function in Python
accompanied by illustrative examples
For those interested in learning Django, a Python web development framework, this cheat sheet is
A Comprehensive Guide on Installing TestNG
an excellent resource. It covers basic syntax , templates, and frequently performed tasks.
in Eclipse with Step-by-Step Instructions

Utilizing Socket Programming in Java


For those interested in expanding their knowledge of Flask, a Python web framework, this cheat
sheet is an ideal resource. It covers fundamental syntax, templates, and helpful suggestions for Utilizing Socket Programming in PHP
typical operations. Programming

Creating 2D Convolution with Python and


For those seeking to expand their knowledge of NumPy, the Python NumPy Cheat Sheet is an ideal NumPy
resource. This tool provides fundamental syntax and standard procedures for manipulating vectors
Adding a User to a Group in Rocky Linux 9: A
and matrices. Step-by-Step Guide

How to install Tomcat 10 on Ubuntu 22.04: A


For those who desire to enhance their understanding of the Matplotlib library, Python data
comprehensive guide
visualization , this cheat sheet is an excellent resource. It contains illustrations that demonstrate
how to generate graphs and plots. Installing Python 3 on Ubuntu 22.04: A Step-
by-Step Guide

A guide to importing data in Python, covering various sources such as text files, databases, file A tutorial for unzipping a Tar Gz file: Step-by-
systems, and more. step guide

A cheat sheet for Jupiter notebooks that includes instructions on saving and loading, utilizing Javascript Tutorials
notebooks with various programming languages, incorporating widgets, and other helpful tips.
Avoid the 'Array findIndex is not a function'
Error in JavaScript: Tips and Tricks
The Keras API is created to be user-friendly, with a focus on minimizing cognitive load. It achieves
this through easy-to-use and consistent APIs, reducing the number of user actions required for How to Validate URLs in JavaScript Using
Regular Expressions - A Comprehensive
common cases, and providing clear error messages. Additionally, Keras has extensive
Guide
documentation and guides for developers.
Discover the Best Methods for Finding the
Index of the Biggest Number in a JavaScript
We trust that the Python cheat sheets have been beneficial to you. In case we have overlooked any,
Array
kindly inform us. Additionally, for further valuable insights and free resources on programming
languages, do visit our blog. Discover the Best Ways to Find an Array
Inside Another Array Using JavaScript

At images.cv, creating image datasets is made simple and hassle-free. With a vast selection of over 10 Must-Know ES6 Features in JavaScript for
15,000 categories to choose from, you can easily find the perfect images for your dataset. Efficient and Maintainable Code

Additionally, our consistent folder structure makes parsing through your dataset a breeze. To make JavaScript Date Comparison: How to Compare
things even easier, we offer advanced tools for pre-processing your data, including the ability to Dates from Different Formats
choose your desired image format, data split, image size, and data augmentation.

👉Visit images.cv to learn more Convert File Sizes with Ease: A


Comprehensive Guide to JavaScript KB to MB
Python Cheat Sheet, Share to Twitter Share to LinkedIn Share to Reddit Share to Hacker News Share t Conversion
o Facebook Share Post via Report Abuse In this post I will give a link to python cheat sheet so you ca
Mastering JSON Data Manipulation with
n access it whenever programming in python. Download cheat sheet. I hope this cheat sheet may he
JavaScript's Map Function
lp you. Be safe and do …
Tag python for web scraping cheat sheet python for data science cheat sheet JavaScript String Manipulation: How to Get
the First Word of a String
s: python importing data cheat sheet

How to Specify Color of Class Using


Ultimate Python Cheat Sheet JavaScript: A Comprehensive Guide

This article provides a helpful memory aid for Python that you won't want to miss.
Artificial Intelligence
Stay updated with my Python posts by following @EricTheCoder_.

Artificial Intelligence

What's artificial intelligence?


Here is my cheat sheet I created along my learning journey. If you have any recommendations (addit
ion/subtraction) let me know. Importance of Artificial Intelligence
Python Cheat Sheet What is artificial intelligence?
naming convention s
How Artificial Intelligence Works?

Uses of Artificial Intelligence


# Variable lower_snake
first_name = 'Mike' How Artificial Intelligence And Natural
# Class and module CamelCase
Intelligence Works
class InvoiceDetail:
# Constant How long has artificial intelligence ai existed
MAX_USER = 100 # All uppercase
Why is artificial intelligence ai gaining
importance
# Indentation : 4 spaces
if num > 9:
Problem Solving in Artificial Intelligence
print('Small number')

New tutorials
Insert a string into other string at the
Data type
specified position or after X paragraphs of a
HTML content in PHP
name = 'Mike' # string
age = 42 # int
Create gradient text with Tailwind CSS
price = 199.99 # float
Sticky Header, Footer and Fixed Sidebar with
is_active = True # boolean
Tailwind CSS
colors = ['red', 'green', 'blue'] # list
states = ('inactive', 'active', 'archive') # tuple How to Install Tailwind CSS in a Laravel
products = { 'name': 'iPad Pro', 'price': 199.99 } # dict Project

How to install Laravel?

Popular PHP Frameworks in 2022

4 tips to solve programming issues


Type conversion
How to Enable Remote Access To MySQL
Database Server?
# Python is a strong type language
number = 50 + "50" # TypeError
Install MySQL 8.0 on Ubuntu 20.04

# Convert to string New command "model:show" in Laravel 9


number = 50 + int("50") # 100

# Convert to string Recommended posts


my_text = str(199.99) # "199.99"
Explaining the Discrepancy between Real
# Convert to number Time and User + System Time in Hadoop
my_number = int(21.99) # 21 Tasks
my_number = float('21.99') # 21.99
Tips for Efficiently Setting Large JSON Files to
Firebase Database using Firebase Tools
# Get type
type(my_text) # Error while building React-native app for
type(my_number) # Android due to missing
com.google.android.gms:play-services-
# Check if number 0 to 9 base:x.y.z
isdigit('8') # True
Proposed Recommendations for Enhancing
# Check type the Security of REST/SOAP Web Services
isinstance(my_number, int) # True
LaTeX for Writing and Organizing Your Thesis

Unit Testing in Visual Studio Fails to Execute

Projective bundles are implied by the


vanishing of the Brauer group combined with
Strings geometric fibers $\mathbb P^n$

Discovering sets of three numbers that add


name = 'Mike'
up to a specific value through recursive
# or
means
name = "Mike"
# or Encountering a 'Expected BEGIN_OBJECT but
message = """This is multiline was STRING at line 1' error while working with
string that is easier to a multi-layered JSON
read and assign"""
# escape characters \n will do a line break
Ensuring Proper Connection Maintenance
message = "Hello \nWorld"
from a C# Client
# raw string (ignore escape characters)
Map parameter type is not supported by
message = r"https:\\example.com\index.html"
future methods
# Convert to lower case
name.lower() # mike
Assessing the definite integral of $\frac{x}
{\sin x}$ over the interval $[-\pi/4, \pi/4]$
# Convert to upper case
name.upper() # MIKE Eliminating the 'No Data' Error in MySql

# Convert first char to Capital letter


Is it possible to utilize the same code for
name.capitalize() # Mike
multiple components of a Chrome Extension?

Difficulty in defining preferred excel


# Convert first char of all words to Capital letter
background color through openxml
name = 'mike taylor'
name.title() # Mike Taylor API Versioning using Attribute Routing in Web
API 2
# Chain methods
name = 'MIKE'
Calculating Subnets within AWS VPC CIDR
name.lower().capitalize() # Mike
Range

Converting []string to []rune: A Guide


name = 'Mike'
# Start with ? Can the existence of a conjecture with the
name.startswith('M') # true largest prime gaps be confirmed?

# End with ?
Ionic app fails to detect web context with new
name.endswith('ke') # true Chrome (v 83)

Unpacking gzip during reception of response


# String length
with http2 library
len(name) # 4
Restructuring a 2D Numpy Array into a 3D
# String concatenation Array
full_name = first_name + ' ' + last_name
# String format
Executing an ipython notebook in parallel by
full_name = f"{first_name} {last_name}"
modifying specific parameter values
# String format number (2 decimal point)
Debug flag not being set? Try using an
number = 12.9997
alternative Docker Compose file and running
number_string = "{:.2f}".format(number) # '12.99'
Django check

# Remove leading and trailing characters (like space or \n) Priority inquiry regarding C++ operators
text = ' this is a text with white space ' address of and scope resolution
text.strip() # 'this is a test with white space'
Unit Testing Kotlin Functions with Parameters
name = 'Mike'
and Objects
# Get string first character
Spotlighting the Current Anchor Link
name[0] # M
Limiting User Selection to a Single Item in
# Get string last character Android's Recycle View
name[-1] # e
Distinctions between mysql-python from pip
# Get partial string
and python-mysqldb from apt-get
name[1:3] # ik
Preserving original permissions with Rsync

# Replace
name.replace('M', 'P') # Pike

# Find (return pos or -1 if not found)


name.find('k') # 2

# List to string
colors = ['red', 'green', 'blue']
', '.join(colors) # 'red, green, blue'

Commons fonctions

# Print to console
print('Hello World')
# Print multiple string
print('Hello', 'World') # Hello World

# Multiple print
print(10 * '-') # ----------

# Variable pretty printer (for debug)


from pprint import pprint
pprint(products) # will output var with formatting
# Get keyboard input
name = input('What is your name? ')
# Random (between 0 and 1)
from random import random
print(random()) # 0.26230234411558273

# Random beween x and y


from random import randint
print(randint(3, 9)) # 5

# Rounding
number = 4.5
print(round(number)) # 5

number = 4.5163
print(round(number, 2)) # 4.52

# Path
import os
current_file_path = __file__
folder_name = os.path.dirname(current_file_path)
new_path = os.path.join(folder_name, 'new folder')
# Round number
solution = round(12.9582, 2) # 12.96

Conditionals

if x == 4:
print('x is 4')
elif x != 5 and x < 11:
print('x is between 6 and 10')
else:
print('x is 5 or greater than 10')
#In or not in
colors = ['red', 'green', 'blue', 'yellow']
if 'blue' in colors:
if 'white' not in colors:
# Ternary
print('y = 10') if y == 10 else print('y != 10')
# ShortHand Ternary
is_valid = 'Valid'
msg = is_valid or "Not valid" # 'Valid'

# Falsy
False, None, 0, empty string "", empty list [], (), {}
# Truthy
True, not zero and not empty value

Interations

# iterating over a sequence (list, string, etc.)


for item in items:
print(item)
# With index
for index, item in enumerate(items):
print(index, item)
# Range
for i in range(10): #0..9
print(i)
for i in range(5, 10): #5..9
print(i)
# While loop
while x > 10:
print(x)
# exit loop
if x == 5:
break
# Jump to next while
if x == 3:
continue
x += 1
# For loop dic
for key, value in my_dict.items():
print(key, value)
# List comprehension:
# values = [(expression) for (value) in (collection)]
items = [value*2 for value in items]
# List comprehension filtering
# values = [expression for value in collection if condition]
even_squares = [x * x for x in range(10) if x % 2 == 0]

List and Tuple

# Create a list
fruits = ['orange', 'apple', 'melon']
# Append to List
fruits.append('banana')
# List length
nb_items = len(fruits)
# Remove from list
del fruits[1] #remove apple

# List access
fruits[0] # first item
fruits[-1] # last item

# Slice my_list[start:finish:step] ([::-1] reverse list)


fruits = fruits[1:3]
fruits[:3] # first 3
fruits[2:] # last 2
copy_fruits = fruits[:] # copy

# List length
nb_entry = len(fruits)
#Create list from string
colors = 'red, green, blue'.split(', ')
# Array concact
color1 = ['red', 'blue']
color2 = ['green', 'yellow']
color3 = color1 + color2
# Concat by unpacking
color3 = [*color1, *color2]
# Multiple assignment
name, price = ['iPhone', 599]
#Create a Tuple (kind of read only list)
colors = ('red', 'green', 'blue')
# Sort
colors.sort() # ['blue', 'green', 'red']
colors.sort(reverse=True) # ['red', 'green', 'blue']
colors.sort(key=lambda color: len(color)) # ['red', 'blue', 'green']

Dictionaries

# Create a empty dict


product = {}
#Create a dict with key/value
product = {'id': 100, 'name': 'iPadPro'}
# Access dict value by key
print(product['name']) # iPadPro

# Access dict
product.get('name') # if key not exist return None
product.get('name', 'default value') # if key not exist return default value

# Adding a new key/value


product['description'] = "Modern mobile device"
# Get dict keys
product.keys() # ['id', 'name', 'description']

# Get dic values


product.values() # ['100', 'iPadPro', 'Modern mobile device']

# Create a list of dict


products = [
{'id': 100, 'name': 'iPadPro'},
{'id': 200, 'name': 'iPhone 12'},
{'id': 300, 'name': 'Charger'},
]
# Access list of dict
print(products[2]['name']) # Charger

# Search list dict


items_match = [item for product in products if product['id'] == 300]
# [{'id': 300, 'name': 'Charger'}]

# Sum list dict


total = sum([product['price'] for product in products])

Functions

# Create a function
def say_hello():
print('Hello World')
# Function with argument (with default value)
def say_hello(name = 'no name'):
print(f"Hello {name}")
# Function with argument (with optional value)
def say_hello(name = None):
if name:
print(f"Hello {name}")
else:
print('Hello World')
# Call a function
say_hello('Mike') # Hello Mike

# Call using keyword argument


say_hello(name = 'Mike')
# Function returning a value
def add(num1, num2):
return num1 + num2
num = add(10, 20) # 30

# Arbitrary numbers of arguments *args


def say_hello(*names):
for name in names:
print(f"Hello {name}")
# Arbitrary numbers of keywords arguments **kwargs
def say_hello(**kwargs):
print(kwargs['name'])
print(kwargs['age'])
say_hello(name = 'Mike', age = 45)
# Lambda function
x = lambda num : num + 10
print(x(20)) # 30

Date and time

from datetime import datetime, timedelta


# Return the current date and time.
datetime.now()
# Create a date time object
date = datetime(2020,12,31) # Dec 31 2020
# Add to date/time (weeks, days, hours, minutes, seconds)
new_year = date + timedelta(days=1) # Jan 1 2021

# Format a date to string


new_year.strftime('%Y/%m/%d %H %M %S') # 2021/01/01 00 00 00
new_year.strftime('%A, %b %d') # Friday, Jan 01

# Extract from date


year = new_year.year # 2021
month = new_year.month # 01

File

# Reading a file and storing its lines


filename = 'demo.txt'
with open(filename) as file:
lines = file.readlines()
for line in lines:
print(line)
# Writing to a file
filename = 'settings.txt'
with open(filename, 'w') as file:
file.write("MAX_USER = 100")
# File exist?
from os import path
path.exists('templates/index.html') # True/False

# CSV
import csv
csv_file = 'export.csv'
csv_columns = products[0].keys() # ['id', 'name']
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
writer.writeheader()
for item in products:
writer.writerow(item)

Catching an exception

age_string = input('Your age? ')


try:
age = int(age_string)
except ValueError:
print("Please enter a numeric value")
else:
print("Your age is saved!")

OOP

# Create a class
class Product:
pass
# Class attribute
class Product:
nb_products = 0
print(Product.nb_products) # 0

# Create new object instance


product_1 = Product()
# Object instance attributes
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
# Create instance with attributes
product_1 = Product('iPadPro', 699.99)
product_2 = Product('iPhone12', 799.99)
print(product_1.name) # iPadPro

# instance method
class Product()
def display_price(self):
return f"Price : {self.price}"
print(product_1.display_price())
# class method
class Product:
# ...
@classmethod
def create_default(cls):
# create a instance
return cls('Product', 0) # default name, default price

product_3 = Product.create_default()
# static method
class Product:
# ...
@staticmethod
def trunc_text(word, nb_char):
return word[:nb_char] + '...'
product_3 = Product.trunc_text('This is a blog', 5) # This i...

# Python Inheritance
class WebProduct(Product):
def __init__(self, name, price, web_code):
super().__init__(name, price)
self.web_code = web_code
# Private scope (naming convention only)
def __init__(self, price):
self.__price = price
# Getter and setter
class Product:
def __init__(self):
self.__price = 0
@property
def price(self):
return self.__price
@price.setter
def price(self, value):
self.__price = value
# Mixins
class Mixin1(object):
def test(self):
print "Mixin1"
class Mixin2(object):
def test(self):
print "Mixin2"
class MyClass(Mixin2, Mixin1, BaseClass):
pass
obj = MyClass()
obj.test() # Mixin2

Module import

from my_module import my_function


# import local file (same folder)
# my_module.py will be the file name
# my_function is a function inside my_module.py

To stay updated on my upcoming Python posts, make sure to follow @EricTheCoder_ and don't miss
out.
Here is my cheat sheet I created along my learning journey. If you have any recommendations (addit
ion/subtraction) let me know.
Python cheat.sheet Code Example, Best Python Cheat Sheet PDF: https://websitesetup.org/wp-conte
nt/uploads/2020/04/Python-Cheat-Sheet.pdf

Python Cheat Sheet for Beginners


You can access these cheatsheets on my GitHub page. Additionally, feel free to enhance this
repository on GitHub by making contributions to it.

Download PDF from here

This reference sheet comprises fundamental Python concepts, while Part 2 will feature more
advanced Python concepts that I will upload.

Python Cheatsheet for Beginners

Table of Content

Beginner's Guide to Python Cheatsheet " Learn the following Python Cheatsheet basics through t
hese 34 tips: -

Basics

Arithmetic Operations

Basic Data Types

Taking User Input

Strings

Creating String

String Concatenation

String Replication

Lists

Combine Two List

Nested List

Sorting List

Copy a List

Tuples

Convert tuple to list

Sets

Creating a Set

Set Operations
-

Dictionaries

Creating Dictionaries

Dictionary Operations

Conditional Statements

If Statement

Elif Statement

Else Statement

Loops

While Loops

For Loop

Functions

Creating a Function

Calling Function

Passing Arguments

Lambda Functions

## This cheatsheet is still in progress

Credits

Basics

Arithmetic Operations

>>> 5 + 2 # Addition
7

>>> 4 - 3 # Subtraction
1

>>> 4 * 4 # Multiplication
16
>>> 10 / 2 # Division
5.0 # Return float value

>>> 10 // 2 # Division, but return integer value


5

>>> 10 % 2 # Modulas(Remainder)
0

>>> 2 ** 3 # Exponenet(Power)
8

Basic Data Types

Data Type Example

Integer ` -2,-1,0,1,2 `

Float ` -1.5, -1.92, 2.25, 16.4 `

String The codes ` 'python' ` , ` 'is' ` , and ` 'love' ` are listed.

Complex ` 1+2j ` is accompanied by ` 1j ` .

Boolean ` x = True ` , followed by ` x = False ` .

Taking User Input

The function input() is utilized for obtaining user input.

name = input("Enter Your Name:")


print("Hello " + name)

Strings

Creating String

myString = "Python is easy!"

String Concatenation

One can concatenate two strings by using the "+" operator.

myString = "Python"
myString2 = "is easy"
ConString = myString + myString2
print(ConString)

String Replication

string = "Python" * 5
print(string)
# OUTPUT: PythonPythonPythonPythonPython
Lists

A list is a variable that can hold multiple items and is created using square brackets . It allows for
changeable elements, can have duplicates, and has a defined order that remains constant. Any new
element added to the list will be placed at the end, and the list index starts at 0 and ends at n-1,
where n is the number of elements.

Generating a Roster

lst = ["python","cpp","java"]

Retrieving data from a List.

>>> lst = ["python","cpp","java"]


>>> lst[0]
"python"
>>> lst[1]
"cpp"
>>> lst[2]
"java"

Incorporating Entries into a Roster

lst = [1,2,3]
lst.append(4)
print(lst)
# OUTPUT : [1, 2, 3, 4]

The second method involves utilizing the insert() function to add an item to a particular index.

lst = [1,3,4]
# SYNTAX : .insert(index number, element)
lst.insert(1,2)
print(lst)
# OUTPUT : [1,2,3,4]

Eliminating Entries from Roster

lst = [1,2,3,5]
lst.remove(5)
print(lst)
# OUTPUT : [1,2,3]

Combine Two List

lst1 = [1,2,3]
lst2 = ["x","y","z"]
combineList = lst1 + lst2
print(combineList)
# OUTPUT: [1, 2, 3, "x", "y", "z"]

Nested List
lst1 = [1,2,3]
lst2 = ["x","y","z"]
nestedList = [list1,list2]
print(nestedList)
# OUTPUT : [[1, 2, 3], ["x", "y", "z"]]

Sorting List

lst = [123,51,214,23,56]
lst.sort()
print(lst)
#OUTPUT : [23, 51, 56, 123, 214]

Copy a List

lst = ["a","b","c"]
lstcpy = lst.copy()
print(lstcpy)
# OUTPUT: ["a", "b", "c"]

Tuples

Tuples and lists have similarities, but tuples are immutable and the values stored in tuple. Tuple
cannot be changed. Tuples are defined using round brackets.

Generating a Tuple.

myTuple = (1,2,3,4)
print(myTuple)

To retrieve a specific item from a tuple, you can simply refer to its index number.

myTuple = (1,2,3,4)
print(myTuple[2])
# OUTPUT: 3

Convert Tuple to List

As Tuples are unchangeable, one alternative is to convert them into a list, make the necessary
modifications, and then convert them back into a tuple.

myTuple = (1,2,3)
convertedTuple = list(myTuple)
# Now we can edit the "convertedTuple" list.
convertedTuple[0] = 120
# Converting back to Tuple.
myTuple = tuple(ConvertedTuple)
print(myTuple)
# OUTPUT: (120,2,3)

Sets

Sets are a useful way to store multiple items within a single variable. They are a type of collection
that is both unordered and unindexed, and are denoted using curly brackets. One notable aspect of
sets is that they do not allow for duplicate values. Additionally, sets can contain a variety of different
data types.

Creating a Set

mySet = {"python", "java", "cpp"}


print(mySet)

Set Operations

A Collection Containing Various Data Types.

mySet = {"python",142,True,"abc"}

Incorporating an Item into a Group

mySet = {1,2,3}
s.add(4)
print(s)
# OUTPUT: {1,2,3,4}

Incorporating Multiple Items into a Set.

mySet = {1,2,3}
mySet.update([4,5,6,7])
print(mySet)
# OUTPUT : {1,2,3,4,5,6,7}

Dictionaries

Dictionaries are utilized for storing information in pairs comprising a key and a corresponding value.
These pairs are unique, modifiable, and ordered. In case of any duplicate values, the dictionary
overwrites the existing values.

Creating Dictionaries

# SYNTAX

# dictionary_name = {
# "key_name" : "Value",
# "key2_name" : "Value2"
# }

dict = {
"name" : "Van Rossum",
"ID" : 1234,
"year" : 1956
}

Dictionary Operations

Producing Documents

print(dict["name"])

Dictionary Size
print(len(dict))
# OUTPUT : 2

Incorporating Entries

dict = {
"name" : "Van Rossum",
"ID" : 1234,
"year" : 1956
}
# Adding Item
dict["profession"] = "Programmer"

Modifying the Object

# Syntax
# dict_name.update({"key":"value"})

dict.update({"ID":"9493"})

Display the values of all items.

for i in dict:
print(dict[i])
# OUTPUT:
# Van Rossum
# 9493
# 1956

Conditional Statements

If Statement

The ` If ` code consists of a logical expression that compares data and leads to a decision.

if expression:
statements or code
Note : Indentation is required in IF statement

# Let's a create a program to check if person is eligible to vote or not

age = 15
if age < 18: # If age is less than 18 execute the block
print("Not Eligible to Vote")
if age >= 18: # If age is greater than or equal to 18 execute the block
print("Eligible to Vote")
# Here age is 15 so, 1st condition will be true and print the message.

Elif Statement

The ` Elif ` is utilized as a fallback option in case the preceding ` if ` condition evaluates to false,
allowing the ` elif ` condition to be executed.
# Let's take the same example but using elif condition
age = 20
if age < 18:
print("Not Eligible to Vote")
elif age >= 18:
print("Eligible to Vote")
#OUTPUT: Eligible to Vote

Else Statement

When all prior conditions are untrue, the ` else ` keyword will activate the ` else ` block.

# Let us Understand using example of "If Number is +ve or -ve."

n = 0
if n > 0:
print("N is +ve")
elif n < 0:
print("N is -ve")
# In this case both the 'if' condition is false so we use 'else' block
else:
print("N is Zero")
# OUTPUT: N is Zero

Loops

Loops are utilized to execute a specific task repeatedly until a certain condition is met. For instance,
in order to print "Hello World" multiple times, instead of writing the print statement repeatedly, we
can make use of loops to accomplish the same task.

While Loops

# print hello World 100 times

i = 1
while i <= 100:
print("Hello World")
i=i+1

For Loop

# Same example but using for loop

# for i in range(101)-> range function is used instead of "i<=100" from while loop
# Syntax for range() function -> range(n-1), So If n=100, range will only include 99.

for i in range(101):
print("Hello World")

Explore additional information regarding the Range() function by clicking here.

Functions

Code blocks that execute only upon being called are known as functions and are defined using the `
def ` keyword.

Creating a Function

SYNTAX
def function_name():
code inside function
def my_function():
print("Hello World")

Calling Function

def greeting():
print("Good Morning")
# Calling Of Function
greeting()

Passing Arguments

# let us understand using example


# -> Take username and greet

# passing name argument


def greet(name):
print("Hello " + name + ", Good Morning" )
greet("Rohan")
## Passing Two Arguments:

def greet(name, lastname):


print("Hello " + name + lastname + ", Good Morning" )
greet("Rohan", "Kiratsata")

Lambda Functions

A lambda function, also known as an anonymous function, is a function without a name and is
typically small in size.

SYNTAX
lambda arguments: expression

# Lambda function to square of number

n = lambda x : x*x
print(n(5))

This cheatsheet is still in progress

Credits

Rohan Kiratsata is the author and overseer of this cheat sheet.

If you feel like there's something lacking, you can enhance this repository by contributing.

Python Cheat Sheet Part, Share to Twitter Share to LinkedIn Share to Reddit Share to Hacker News Sh
are to Facebook Share Post via Report Abuse. sandeepk27. Posted on May 1. Python Cheat Sheet Par
t - 2 Python Cheat Sheet Part - 4 # beginners # programming # tutorial # python. Python Cheat She
et Part

Read other technology post: Javascript toggle play pause button videojs code example

Related posts:
Python python cheat sheet for beginners code example

Python what is the meaning of in python

Write a comment:

Your name Title

Message

Please login to Send

© CopyProgramming 2023 - All right reserved About us Terms of Service Privacy Contact

You might also like