Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views5 pages

Python Cheatsheet

The document provides various examples of iterating over lists, strings, dictionaries, and sets in Python, demonstrating how to add, update, and delete elements. It also covers the use of lambda functions, map, zip, and groupby for transforming and grouping data. Additionally, it includes examples of using generators and decorators to enhance function behavior.

Uploaded by

vaibhavag404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Python Cheatsheet

The document provides various examples of iterating over lists, strings, dictionaries, and sets in Python, demonstrating how to add, update, and delete elements. It also covers the use of lambda functions, map, zip, and groupby for transforming and grouping data. Additionally, it includes examples of using generators and decorators to enhance function behavior.

Uploaded by

vaibhavag404
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

# Example: Iterating over a list without index

fruits = ['apple', 'banana', 'cherry']

for fruit in fruits:


print(fruit)

# Example: Iterating over a list with index


fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):


print(f"Index: {index}, Fruit: {fruit}")

# Example: Iterating over a string without index


greeting = "Hello"

for char in greeting:


print(char)

# Example: Iterating over a dictionary with index


person = {'name': 'Alice', 'age': 30, 'city': 'New York'}

for index, (key, value) in enumerate(person.items()):


print(f"Index: {index}, Key: {key}, Value: {value}")

# List example
my_list = [1, 2, 3]

# Adding values
my_list.append(4) # Add to the end
my_list.insert(1, 1.5) # Insert at index 1
print("After adding:", my_list)

# Updating values
my_list[1] = 1.6 # Update value at index 1
print("After updating:", my_list)

# Deleting values
my_list.remove(1.6) # Remove the rst occurrence of 1.6
popped_value = my_list.pop(2) # Remove and return the element at index 2
del my_list[0] # Delete the element at index 0
print("After deleting:", my_list)

# Dictionary example
my_dict = {'a': 1, 'b': 2}

# Adding/Updating values
my_dict['c'] = 3 # Add new key-value pair
my_dict.update({'d': 4, 'e': 5}) # Update multiple key-value pairs
print("After adding/updating:", my_dict)

# Deleting values
del my_dict['a'] # Delete key-value pair with key 'a'
popped_value = my_dict.pop('b') # Remove and return value associated with key 'b'
my_dict.popitem() # Remove and return an arbitrary key-value pair
print("After deleting:", my_dict)

# Set example
my_set = {1, 2, 3}
fi
# Adding values
my_set.add(4) # Add a single element
my_set.update({5, 6}) # Add multiple elements
print("After adding:", my_set)

# Deleting values
my_set.remove(4) # Remove element 4
my_set.discard(5) # Remove element 5 if it exists
popped_value = my_set.pop() # Remove and return an arbitrary element
my_set.clear() # Remove all elements
print("After deleting:", my_set)

# Original list with duplicates


original_list = [4, 2, 5, 2, 3, 1, 4, 5, 6, 3]

# Step 1: Convert the list to a set to remove duplicates


unique_set = set(original_list)

# Step 2: Convert the set back to a list


unique_list = list(unique_set)

# Step 3: Sort the list


unique_list.sort()

# Print the result


print("Sorted list with duplicates removed:", unique_list)

# Original list with duplicates


original_list = [4, 2, 5, 2, 3, 1, 4, 5, 6, 3]

# Step 1: Convert the list to a set to remove duplicates


unique_set = set(original_list)

# Step 2: Use sorted() to create a new sorted list


sorted_unique_list = sorted(unique_set)

# Print the result


print("Sorted list with duplicates removed:", sorted_unique_list)

# Original list of numbers


numbers = [1, 2, 3, 4, 5]

# Lambda function to square a number


square_lambda = lambda x: x ** 2

# Use map() to apply the lambda function to each element in the list
squared_numbers = list(map(square_lambda, numbers))

# Print the result


print("Original list:", numbers)
print("Squared list:", squared_numbers)

# Original list of strings


strings = ["apple", "banana", "cherry"]

# Lambda function to convert a string to uppercase


uppercase_lambda = lambda s: s.upper()

# Use map() to apply the lambda function to each element in the list
uppercase_strings = list(map(uppercase_lambda, strings))

# Print the result


print("Original list:", strings)
print("Uppercase list:", uppercase_strings)

# Original list of numbers


numbers = [1, 2, 3, 4, 5]

# Lambda function to square a number and add 1


transform_lambda = lambda x: (x ** 2) + 1

# Use map() to apply the lambda function to each element in the list
transformed_numbers = list(map(transform_lambda, numbers))

# Print the result


print("Original list:", numbers)
print("Transformed list:", transformed_numbers)

# Original lists of numbers


list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]

# Lambda function to add two numbers


add_lambda = lambda x, y: x + y

# Use zip() to pair elements from both lists and map() to apply the lambda function
transformed_list = list(map(add_lambda, list1, list2))

# Print the result


print("List 1:", list1)
print("List 2:", list2)
print("Transformed list (sum of corresponding elements):", transformed_list)

# Original lists of numbers


list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]

# Lambda function to multiply two numbers


multiply_lambda = lambda x, y: x * y

# Use zip() to pair elements from both lists and map() to apply the lambda function
transformed_list = list(map(multiply_lambda, list1, list2))

# Print the result


print("List 1:", list1)
print("List 2:", list2)
print("Transformed list (product of corresponding elements):", transformed_list)

# Original lists of numbers


list1 = [1, 2, 3, 4, 5]
list2 = [10, 20, 30, 40, 50]
list3 = [100, 200, 300, 400, 500]

# Lambda function to sum three numbers


sum_lambda = lambda x, y, z: x + y + z

# Use zip() to pair elements from all three lists and map() to apply the lambda function
transformed_list = list(map(sum_lambda, list1, list2, list3))
# Print the result
print("List 1:", list1)
print("List 2:", list2)
print("List 3:", list3)
print("Transformed list (sum of corresponding elements):", transformed_list)

# Original list of characters


char_list = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

# Merge the list of characters into a single string using join()


merged_string = ''.join(char_list)

# Print the result


print("Original list of characters:", char_list)
print("Merged string:", merged_string)

# Original list of characters


char_list = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']

# Merge the list of characters into a single string with a separator


merged_string_with_separator = '-'.join(char_list)

# Print the result


print("Original list of characters:", char_list)
print("Merged string with separator:", merged_string_with_separator)

from itertools import groupby

# Original list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Sort the list by the key function (even or odd)


numbers.sort(key=lambda x: x % 2)
transformed_list.sort(key=lambda x: x % 10, reverse = True)

# De ne a key function to group by even or odd


key_func = lambda x: 'even' if x % 2 == 0 else 'odd'

# Group the numbers using groupby


grouped_numbers = {key: list(group) for key, group in groupby(numbers, key=key_func)}

# Print the result


print("Grouped numbers by even/odd:", grouped_numbers)

# Original list of numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Initialize an empty dictionary to store groups


grouped_numbers = {'even': [], 'odd': []}

# Iterate over the list and group the numbers


for number in numbers:
if number % 2 == 0:
grouped_numbers['even'].append(number)
else:
grouped_numbers['odd'].append(number)

#Generators

def bonacci_generator(n):
fi
fi
a, b = 0, 1
count = 0
while count < n:
yield a
a, b = b, a + b
count += 1

# Using the generator


b_gen = bonacci_generator(10)
for num in b_gen:
print(num)

# Decorators
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__} with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"Function {func.__name__} returned: {result}")
return result
return wrapper

@log_function_call
def add(a, b):
return a + b

@log_function_call
def multiply(x, y):
return x * y

# Using the decorated functions


sum_result = add(5, 3)
product_result = multiply(4, 6)
fi
fi
fi

You might also like