Monday, 11 December 2023

List and Dictionary Comprehensions


List Comprehensions

List Comprehensions execute from Right to Left , here first it will execute this for loop  for x in [1,2,3] and assign to variable same as for y variable it follows where x!=y

 >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

Above statement is equal to below statement 

combs = []
for x in [1,2,3]:
    for y in [3,1,4]:
        if x != y:
            combs.append((x, y))


combs

[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

#########################################################################

You can use a function in a list comprehension to apply a transformation or filter elements based on a condition

>>> # Example 1: Using a function to square each element in a list
>>> def square(x):
...     return x ** 2
...
>>> numbers = [1, 2, 3, 4, 5]
>>> squared_numbers = [square(num) for num in numbers]
>>> print(squared_numbers)
[1, 4, 9, 16, 25]
>>> # Output: [1, 4, 9, 16, 25]
>>>

#################################################################################
Dictionary comprehensions in Python allow you to create dictionaries in a concise and readable way

>>> number = [1,2,3,4,6,7,8,6]
>>> dc={i:i*i for k in number}

>>> dc={i:i*i for i in number}
>>> print(dc)
{1: 1, 2: 4, 3: 9, 4: 16, 6: 36, 7: 49, 8: 64}
>>>
#################################################################################

No comments:

Post a Comment

SQL -

 Window Functions -  Window function: pySpark window functions are useful when you want to examine relationships within group of data rather...