enumerate()
The enumerate()
function in Python is used to iterate over a sequence (such as a list, tuple, or string) while keeping track of the index position of each item. It returns an List , which contains pairs of index and value tuple .
Here's how you can use enumerate()
:
my_list = ['apple', 'banana', 'orange']
for index, value in enumerate(my_list):
print(f"Index: {index}, Value: {value}")
This will output:
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
You can also specify a start index for enumeration:
my_list = ['apple', 'banana', 'orange']
for index, value in enumerate(my_list, start=1):
print(f"Index: {index}, Value: {value}")
This will output:
Index: 1, Value: apple
Index: 2, Value: banana
Index: 3, Value: orange
Using enumerate()
can be quite handy, especially when you need both the index and value of items in a sequence.
zip()
zip()
is a Python built-in function that is used to combine elements from multiple iterables (such as lists, tuples, or strings) into tuples. It takes iterables as input and returns an iterator of tuples where the i-th tuple contains the i-th element from each of the input iterables.
Here's a basic example of how zip()
works:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
zipped = zip(list1, list2)
print(list(zipped)) # Output: [('a', 1), ('b', 2), ('c', 3)]
In this example, zip(list1, list2)
combines elements from list1
and list2
into tuples, pairing the elements based on their respective positions.
It's worth noting that if the input iterables are of different lengths, zip()
will only combine elements until the shortest iterable is exhausted. Any remaining elements in the longer iterables will be ignored.
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3, 4, 5]
zipped = zip(list1, list2)
print(list(zipped)) # Output: [('a', 1), ('b', 2), ('c', 3)]
In this case, the fourth and fifth elements of list2
are ignored because list1
only has three elements.
zip()
can also be used with more than two iterables:
list1 = ['a', 'b', 'c']
list2 = [1, 2, 3]
list3 = ['x', 'y', 'z']
zipped = zip(list1, list2, list3)
print(list(zipped)) # Output: [('a', 1, 'x'), ('b', 2, 'y'), ('c', 3, 'z')]
Here, zip()
combines elements from list1
, list2
, and list3
into tuples.
If you want to zip together characters of two strings into tuples, you can simply pass the strings as arguments to the zip()
function. Here's how you can do it:
pythonCopy codestr1 = "hello"
str2 = "world"
zipped = zip(str1, str2)
print(list(zipped)) # Output: [('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd')]
In this example, each character from str1
is paired with the corresponding character from str2
to form tuples. If one of the strings is longer than the other, zip()
will only zip up to the length of the shortest string.
Comprehensions
Comprehensions are a concise and expressive way to create sequences (lists, sets, dictionaries) by applying an operation to each item in another iterable. They provide a more readable and often more efficient alternative to using traditional loops.
Types of Comprehensions
List Comprehensions: List comprehensions create lists by iterating over an iterable and applying an expression to each element.
squares = [x**2 for x in range(10)]
Set Comprehensions: Set comprehensions create sets by iterating over an iterable and applying an expression to each element.
squares_set = {x**2 for x in range(10)}
Dictionary Comprehensions: Dictionary comprehensions create dictionaries by iterating over an iterable and creating key-value pairs using expressions.
squares_dict = {x:x**2 for x in range(10)}
Syntax
The general syntax for comprehensions is:
[expression for item in iterable if condition]
expression
: The operation to be applied to each item.item
: The variable representing each item in the iterable.iterable
: The collection of items over which iteration occurs.condition
(optional): An additional filter to include only items that meet certain criteria.
Example
Let's create a list of even numbers from 0 to 9 using a list comprehension:
even_numbers = [x for x in range(10) if x % 2 == 0]
print(even_numbers) # Output: [0, 2, 4, 6, 8]
In this example:
x
is the item in the iterable (range(10)
).for x in range(10)
iterates over numbers from 0 to 9.if x % 2 == 0
filters out only even numbers.x
is the expression to be included in the list.
Benefits
Readability: Comprehensions make code more concise and readable compared to traditional loops.
Efficiency: Comprehensions are often more efficient than equivalent loops.
Expressiveness: Comprehensions allow expressing the intent of the code more clearly.
Understanding and mastering comprehensions can greatly enhance your productivity and code quality in Python.
Nested Comprehensions
Nested comprehensions allow you to create sequences of sequences, such as lists of lists, sets of sets, or dictionaries of dictionaries, by using one or more comprehensions inside another comprehension. Let's explore each type:
List of Lists
You can create a list of lists using nested list comprehensions. Here's an example to create a 3x3 matrix initialized with zeros:
matrix = [[0 for _ in range(3)] for _ in range(3)]
print(matrix)
# Output:
# [[0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]]
In this example, the inner comprehension [0 for _ in range(3)]
creates a row of three zeros, and the outer comprehension [[0 for _ in range(3)] for _ in range(3)]
creates three such rows, forming the 3x3 matrix.
Set of Sets
Similarly, you can create a set of sets using nested set comprehensions. Here's an example to create a set of sets containing the first three multiples of each number from 1 to 3:
multiples_set = {{num * i for i in range(1, 4)} for num in range(1, 4)}
print(multiples_set)
# Output: {{1, 2, 3}, {2, 4, 6}, {3, 6, 9}}
In this example, the inner comprehension {num * i for i in range(1, 4)}
creates a set containing the first three multiples of num
, and the outer comprehension {{num * i for i in range(1, 4)} for num in range(1, 4)}
creates three such sets, forming the set of sets.
one example :
# n = int(input())
#
# score_dataset = []
# for i in range(n):
# D = {}
# D["name"] = input()
# D["city"] = input()
# D["seq_no"] = int(input())
# D["maths"] = int(input())
# D["physics"] = int(input())
# D["chemistry"] = int(input())
# score_dataset.append(D)
#
# print(score_dataset)
score_dataset = [
{
"name": input(),
"city": input(),
"seq_no": int(input()),
"maths": int(input()),
"physics": int(input()),
"chemistry": int(input()),
}
for i in range(int(input()))
]
print(score_dataset)
Dictionary of Dictionaries
You can also create a dictionary of dictionaries using nested dictionary comprehensions. Here's an example to create a dictionary where keys are integers from 1 to 3 and values are dictionaries containing their squares and cubes:
dict_of_dicts = {num: {'square': num ** 2, 'cube': num ** 3} for num in range(1, 4)}
print(dict_of_dicts)
# Output: {1: {'square': 1, 'cube': 1}, 2: {'square': 4, 'cube': 8}, 3: {'square': 9, 'cube': 27}}
In this example, the inner comprehension {'square': num ** 2, 'cube': num ** 3}
creates a dictionary containing the square and cube of num
, and the outer comprehension {num: {'square': num ** 2, 'cube': num ** 3} for num in range(1, 4)}
creates three such dictionaries, forming the dictionary of dictionaries.
Nested comprehensions provide a concise and expressive way to construct complex data structures in Python. However, they should be used judiciously to maintain readability and avoid excessive complexity.
n =5
matrix = [
[j for i in range(n)]
for j in range(n)
]
matrix = []
for j in range(n):
matrix.append([j for i in range(n)])
matrix = [
(i,j)
for i in range(n)
for j in range(n)
]
matrix =[]
for i in range(n):
for j in range(n):
matrix.append((i,j))
print(matrix)
Map()
The map()
function in Python is used to apply a specified function to each item in an iterable (such as a list, tuple, or string) and returns an iterator that yields the results. It allows you to perform a certain operation on each item of the iterable efficiently without using a manual loop.
The syntax of the map()
function is as follows:
map(function, iterable)
function
: The function to be applied to each item of the iterable.iterable
: The iterable (e.g., list, tuple, string) whose elements will be passed as arguments to the function.
Here's an example
# Define a function to square a number
def square(x):
return x ** 2
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Apply the square function to each number using map
squared_numbers = map(square, numbers)
# Convert the result to a list and print it
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
Lambda Function
A lambda function in Python is a small anonymous function defined using the lambda
keyword. It's called anonymous because it doesn't have a name like a regular function defined with the def
keyword. Lambda functions can take any number of arguments, but they can only have one expression. Lambda functions are often used as a way to create simple functions on the fly.
Here's the basic syntax of a lambda function:
lambda arguments: expression
Here's an example of a lambda function that adds two numbers:
add = lambda x, y: x + y
result = add(3, 5)
print(result) # Output: 8
In this example, lambda x, y: x + y
creates a lambda function that takes two arguments x
and y
and returns their sum. The add
variable is assigned this lambda function, and then we call add(3, 5)
to compute the sum of 3 and 5.
Lambda functions are often used when you need a simple function for a short period of time, such as when passing a function as an argument to another function (e.g., sorting, filtering, mapping), or when you want to define a function inline without cluttering the code with a separate named function. However, for more complex logic or functions that are used frequently, it's generally better to use regular named functions defined with the def
keyword.
lambda + map + comprehensions
sentence = list("multi level sort - using tuple comparision")
counts = {char:sentence.count(char) for char in set(sentence)}
# from collections import defaultdict
# counts = defaultdict(lambda : 0)
# print(counts)
# for char in sentence:
# counts[char] +=1
# print(dict(counts))
grouping_key = lambda x : counts[x]
count_letters = {count:[] for count in set(map(grouping_key, counts))}
for letter in counts:
count_letters[grouping_key(letter)].append(letter)
count_letters
"""
{1: ['v', 'c', 'a', '-', 'g'],
2: ['r', 'p', 'n', 'm'],
3: ['u', 't', 'o', 'e', 's'],
4: ['i', 'l'],
6: [' ']}
"""