Python for ds 1

Cheat Sheet: Python Basics

Package/MethodDescriptionCode Example
CommentsComments are lines of text that are ignored by the Python interpreter when executing the code<./td>
 
    
  1. 1
  1. # This is a comment
Copied!
ConcatenationCombines (concatenates) strings.Syntax: 
 
    
  1. 1
  1. concatenated_string = string1 + string2
Copied!

Example: 

 
    
  1. 1
  1. result = "Hello" + " John"</td>
Copied!
Data Types- Integer - Float - Boolean - StringExample: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  1. x=7
  2. # Integer Value
  3. y=12.4
  4. # Float Value
  5. is_valid = True
  6. # Boolean Value
  7. is_valid = False
  8. # Boolean Value
  9. F_Name = "John"
  10. # String Value
Copied!
IndexingAccesses character at a specific index.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. char = my_string[0]
Copied!
len()Returns the length of a string.Syntax: 
 
    
  1. 1
  1. len(string_name)
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. length = len(my_string)
Copied!
lower()Converts string to lowercase.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. uppercase_text = my_string.lower()
Copied!
print()Prints the message or variable inside `()`.Example: 
 
    
  1. 1
  2. 2
  1. print("Hello, world")
  2. print(a+b)
Copied!
Python Operators- Addition (+): Adds two values together.
- Subtraction (-): Subtracts one value from another. 
- Multiplication (*): Multiplies two values. 
- Division (/): Divides one value by another, returns a float. 
- Floor Division (//): Divides one value by another, returns the quotient as an integer. 
- Modulo (%): Returns the remainder after division.
Example: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  1. x = 9 y = 4
  2. result_add= x + y # Addition
  3. result_sub= x - y # Subtraction
  4. result_mul= x * y # Multiplication
  5. result_div= x / y # Division
  6. result_fdiv= x // y # Floor Division
  7. result_mod= x % y # Modulo</td>
Copied!
replace()Replaces substrings.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. new_text = my_string.replace("Hello", "Hi")
Copied!
SlicingExtracts a portion of the string.Syntax: 
 
    
  1. 1
  1. substring = string_name[start:end]
Copied!

Example: 

 
    
  1. 1
  1. my_string="Hello" substring = my_string[0:5]
Copied!
split()Splits string into a list based on a delimiter.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. split_text = my_string.split(",")
Copied!
strip()Removes leading/trailing whitespace.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. trimmed = my_string.strip()
Copied!
upper()Converts string to uppercase.Example: 
 
    
  1. 1
  2. 2
  1. my_string="Hello"
  2. uppercase_text = my_string.upper()
Copied!
Variable AssignmentAssigns a value to a variable.Syntax: 
 
    
  1. 1
  1. variable_name = value
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. name="John" # assigning John to variable name
  2. x = 5 # assigning 5 to variable x
Copied!

List

Package/MethodDescriptionCode Example
append()The `append()` method is used to add an element to the end of a list.Syntax: 
 
    
  1. 1
  1. list_name.append(element)
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. fruits = ["apple", "banana", "orange"]
  2. fruits.append("mango") print(fruits)
Copied!
copy()The `copy()` method is used to create a shallow copy of a list.Example 1: 
 
    
  1. 1
  2. 2
  3. 3
  1. my_list = [1, 2, 3, 4, 5]
  2. new_list = my_list.copy() print(new_list)
  3. # Output: [1, 2, 3, 4, 5]
Copied!
count()The `count()` method is used to count the number of occurrences of a specific element in a list in Python.Example: 
 
    
  1. 1
  2. 2
  3. 3
  1. my_list = [1, 2, 2, 3, 4, 2, 5, 2]
  2. count = my_list.count(2) print(count)
  3. # Output: 4
Copied!
Creating a listA list is a built-in data type that represents an ordered and mutable collection of elements. Lists are enclosed in square brackets [] and elements are separated by commas.Example: 
 
    
  1. 1
  1. fruits = ["apple", "banana", "orange", "mango"]
Copied!
delThe `del` statement is used to remove an element from list. `del` statement removes the element at the specified index.Example: 
 
    
  1. 1
  2. 2
  3. 3
  1. my_list = [10, 20, 30, 40, 50]
  2. del my_list[2] # Removes the element at index 2 print(my_list)
  3. # Output: [10, 20, 40, 50]
Copied!
extend()The `extend()` method is used to add multiple elements to a list. It takes an iterable (such as another list, tuple, or string) and appends each element of the iterable to the original list.Syntax: 
 
    
  1. 1
  1. list_name.extend(iterable)
Copied!

Example: 

 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. fruits = ["apple", "banana", "orange"]
  2. more_fruits = ["mango", "grape"]
  3. fruits.extend(more_fruits)
  4. print(fruits)
Copied!
IndexingIndexing in a list allows you to access individual elements by their position. In Python, indexing starts from 0 for the first element and goes up to `length_of_list - 1`.Example: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  1. my_list = [10, 20, 30, 40, 50]
  2. print(my_list[0])
  3. # Output: 10 (accessing the first element)
  4. print(my_list[-1])
  5. # Output: 50 (accessing the last element using negative indexing)
Copied!
insert()The `insert()` method is used to insert an element.Syntax: 
 
    
  1. 1
  1. list_name.insert(index, element)
Copied!

Example: 

 
    
  1. 1
  2. 2
  3. 3
  1. my_list = [1, 2, 3, 4, 5]
  2. my_list.insert(2, 6)
  3. print(my_list)
Copied!
Modifying a listYou can use indexing to modify or assign new values to specific elements in the list.Example: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. my_list = [10, 20, 30, 40, 50]
  2. my_list[1] = 25 # Modifying the second element
  3. print(my_list)
  4. # Output: [10, 25, 30, 40, 50]
Copied!
pop()`pop()` method is another way to remove an element from a list in Python. It removes and returns the element at the specified index. If you don't provide an index to the `pop()` method, it will remove and return the last element of the list by defaultExample 1: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  1. my_list = [10, 20, 30, 40, 50]
  2. removed_element = my_list.pop(2) # Removes and returns the element at index 2
  3. print(removed_element)
  4. # Output: 30
  5. print(my_list)
  6. # Output: [10, 20, 40, 50]
Copied!

Example 2: 

 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  1. my_list = [10, 20, 30, 40, 50]
  2. removed_element = my_list.pop() # Removes and returns the last element
  3. print(removed_element)
  4. # Output: 50
  5. print(my_list)
  6. # Output: [10, 20, 30, 40]
Copied!
remove()To remove an element from a list. The `remove()` method removes the first occurrence of the specified value.Example: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. my_list = [10, 20, 30, 40, 50]
  2. my_list.remove(30) # Removes the element 30
  3. print(my_list)
  4. # Output: [10, 20, 40, 50]
Copied!
reverse()The `reverse()` method is used to reverse the order of elements in a listExample 1: 
 
    
  1. 1
  2. 2
  3. 3
  1. my_list = [1, 2, 3, 4, 5]
  2. my_list.reverse() print(my_list)
  3. # Output: [5, 4, 3, 2, 1]
Copied!
SlicingYou can use slicing to access a range of elements from a list.Syntax: 
 
    
  1. 1
  1. list_name[start:end:step]
Copied!

Example: 

 
    
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  1. my_list = [1, 2, 3, 4, 5]
  2. print(my_list[1:4])
  3. # Output: [2, 3, 4] (elements from index 1 to 3)
  4. print(my_list[:3])
  5. # Output: [1, 2, 3] (elements from the beginning up to index 2)
  6. print(my_list[2:])
  7. # Output: [3, 4, 5] (elements from index 2 to the end)
  8. print(my_list[::2])
  9. # Output: [1, 3, 5] (every second element)
Copied!
sort()The `sort()` method is used to sort the elements of a list in ascending order. If you want to sort the list in descending order, you can pass the `reverse=True` argument to the `sort()` method.Example 1: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. my_list = [5, 2, 8, 1, 9]
  2. my_list.sort()
  3. print(my_list)
  4. # Output: [1, 2, 5, 8, 9]
Copied!

Example 2: 

 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. my_list = [5, 2, 8, 1, 9]
  2. my_list.sort(reverse=True)
  3. print(my_list)
  4. # Output: [9, 8, 5, 2, 1]
Copied!

Dictionary

Package/MethodDescriptionCode Example
Accessing ValuesYou can access the values in a dictionary using their corresponding `keys`.Syntax: 
 
    
  1. 1
  1. Value = dict_name["key_name"]
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. name = person["name"]
  2. age = person["age"]
Copied!
Add or modifyInserts a new key-value pair into the dictionary. If the key already exists, the value will be updated; otherwise, a new entry is created.Syntax: 
 
    
  1. 1
  1. dict_name[key] = value
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. person["Country"] = "USA" # A new entry will be created.
  2. person["city"] = "Chicago" # Update the existing value for the same key
Copied!
clear()The `clear()` method empties the dictionary, removing all key-value pairs within it. After this operation, the dictionary is still accessible and can be used further.Syntax: 
 
    
  1. 1
  1. dict_name.clear()
Copied!

Example: 

 
    
  1. 1
  1. grades.clear()
Copied!
copy()Creates a shallow copy of the dictionary. The new dictionary contains the same key-value pairs as the original, but they remain distinct objects in memory.Syntax: 
 
    
  1. 1
  1. new_dict = dict_name.copy()
Copied!

Example: 

 
    
  1. 1
  2. 2
  1. new_person = person.copy()
  2. new_person = dict(person) # another way to create a copy of dictionary
Copied!
Creating a DictionaryA dictionary is a built-in data type that represents a collection of key-value pairs. Dictionaries are enclosed in curly braces `{}`.Example: 
 
    
  1. 1
  2. 2
  1. dict_name = {} #Creates an empty dictionary
  2. person = { "name": "John", "age": 30, "city": "New York"}
Copied!
delRemoves the specified key-value pair from the dictionary. Raises a `KeyError` if the key does not exist.Syntax: 
 
    
  1. 1
  1. del dict_name[key]
Copied!

Example: 

 
    
  1. 1
  1. del person["Country"]
Copied!
items()Retrieves all key-value pairs as tuples and converts them into a list of tuples. Each tuple consists of a key and its corresponding value.Syntax: 
 
    
  1. 1
  1. items_list = list(dict_name.items())
Copied!

Example: 

 
    
  1. 1
  1. info = list(person.items())
Copied!
key existenceYou can check for the existence of a key in a dictionary using the `in` keywordExample: 
 
    
  1. 1
  2. 2
  1. if "name" in person:
  2. print("Name exists in the dictionary.")
Copied!
keys()Retrieves all keys from the dictionary and converts them into a list. Useful for iterating or processing keys using list methods.Syntax: 
 
    
  1. 1
  1. keys_list = list(dict_name.keys())
Copied!

Example: 

 
    
  1. 1
  1. person_keys = list(person.keys())
Copied!
update()The `update()` method merges the provided dictionary into the existing dictionary, adding or updating key-value pairs.Syntax: 
 
    
  1. 1
  1. dict_name.update({key: value})
Copied!

Example: 

 
    
  1. 1
  1. person.update({"Profession": "Doctor"})
Copied!
values()Extracts all values from the dictionary and converts them into a list. This list can be used for further processing or analysis.Syntax: 
 
    
  1. 1
  1. values_list = list(dict_name.values())
Copied!

Example: 

 
    
  1. 1
  1. person_values = list(person.values())
Copied!

Sets

Package/MethodDescriptionCode Example
add()Elements can be added to a set using the `add()` method. Duplicates are automatically removed, as sets only store unique values.Syntax: 
 
    
  1. 1
  1. set_name.add(element)
Copied!

Example: 

 
    
  1. 1
  1. fruits.add("mango")
Copied!
clear()The `clear()` method removes all elements from the set, resulting in an empty set. It updates the set in-place.Syntax: 
 
    
  1. 1
  1. set_name.clear()
Copied!

Example: 

 
    
  1. 1
  1. fruits.clear()
Copied!
copy()The `copy()` method creates a shallow copy of the set. Any modifications to the copy won't affect the original set.Syntax: 
 
    
  1. 1
  1. new_set = set_name.copy()
Copied!

Example: 

 
    
  1. 1
  1. new_fruits = fruits.copy()
Copied!
Defining SetsA set is an unordered collection of unique elements. Sets are enclosed in curly braces `{}`. They are useful for storing distinct values and performing set operations.Example:
 
    
  1. 1
  2. 2
  1. empty_set = set() #Creating an Empty Set
  2. fruits = {"apple", "banana", "orange"}
Copied!
discard()Use the `discard()` method to remove a specific element from the set. Ignores if the element is not found.Syntax: 
 
    
  1. 1
  1. set_name.discard(element)
Copied!

Example: 

 
    
  1. 1
  1. fruits.discard("apple")
Copied!
issubset()The `issubset()` method checks if the current set is a subset of another set. It returns True if all elements of the current set are present in the other set, otherwise False.Syntax: 
 
    
  1. 1
  1. is_subset = set1.issubset(set2)
Copied!

Example: 

 
    
  1. 1
  1. is_subset = fruits.issubset(colors)
Copied!
issuperset()The `issuperset()` method checks if the current set is a superset of another set. It returns True if all elements of the other set are present in the current set, otherwise False.Syntax: 
 
    
  1. 1
  1. is_superset = set1.issuperset(set2)
Copied!

Example: 

 
    
  1. 1
  1. is_superset = colors.issuperset(fruits)
Copied!
pop()The `pop()` method removes and returns an arbitrary element from the set. It raises a `KeyError` if the set is empty. Use this method to remove elements when the order doesn't matter.Syntax: 
 
    
  1. 1
  1. removed_element = set_name.pop()
Copied!

Example: 

 
    
  1. 1
  1. removed_fruit = fruits.pop()
Copied!
remove()Use the `remove()` method to remove a specific element from the set. Raises a `KeyError` if the element is not found.Syntax: 
 
    
  1. 1
  1. set_name.remove(element)
Copied!

Example: 

 
    
  1. 1
  1. fruits.remove("banana")
Copied!
Set OperationsPerform various operations on sets: `union`, `intersection`, `difference`, `symmetric difference`.Syntax: 
 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. union_set = set1.union(set2)
  2. intersection_set = set1.intersection(set2)
  3. difference_set = set1.difference(set2)
  4. sym_diff_set = set1.symmetric_difference(set2)
Copied!

Example: 

 
    
  1. 1
  2. 2
  3. 3
  4. 4
  1. combined = fruits.union(colors)
  2. common = fruits.intersection(colors)
  3. unique_to_fruits = fruits.difference(colors)
  4. sym_diff = fruits.symmetric_difference(colors)
Copied!
update()The `update()` method adds elements from another iterable into the set. It maintains the uniqueness of elements.Syntax: 
 
    
  1. 1
  1. set_name.update(iterable)
Copied!

Example: 

 
    
  1. 1
  1. fruits.update(["kiwi", "grape"]
Copied!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值