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

More On Python Syntax

The document covers advanced Python syntax, focusing on list comprehension, lambda functions, and built-in functions like map, filter, and reduce. It provides examples for creating lists and dictionaries in a single line, as well as exercises for practice. Additionally, it explains how to use lambda functions for concise coding and demonstrates the use of map, filter, and reduce for various operations.

Uploaded by

SHOVAN ROY
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 views14 pages

More On Python Syntax

The document covers advanced Python syntax, focusing on list comprehension, lambda functions, and built-in functions like map, filter, and reduce. It provides examples for creating lists and dictionaries in a single line, as well as exercises for practice. Additionally, it explains how to use lambda functions for concise coding and demonstrates the use of map, filter, and reduce for various operations.

Uploaded by

SHOVAN ROY
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

More on Python

Syntax
More on Python Syntax
• We’ll be covering one-liners using list comprehension and
anonymous functions. This will help to reduce the lines of
code by condensing the same functionality within a single line.

• Building lists in one line using comprehensions

• Understanding one-line anonymous functions

• Using Python’s built-in functions for list alteration


List Comprehension
• List comprehension allows us to create a list lled with data in a single line.
However, it doesn’t improve performance.
• Syntax
• result = [ transform iteration lter ]
• Example,
• nameList = [ itemToAppend for item in list ]
• nameList = [ itemToAppend for item in list if condition ]

# generates a list from 0 up to 20


nums = []
for x in range(20):
[Link](x) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

print(nums) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

nums = [ x for x in range(20) ] [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

print(nums)

# generates a list of even numbers from 0 up to 20


nums = [ x for x in range(20) if x % 2 == 0 ]
print(nums)
fi
fi
if-else statement
# generates a list of even/odd strings
nums = [ "Even" if x % 2 == 0 else "Odd" for x in range(10) ]
print(nums)

nums = []
for x in range(10):
if x % 2 == 0:
[Link]("Even")
else:
[Link]("Odd")
print(nums)

# creates a new list of squared numbers based on nums


nums = [2, 4, 6, 8]
squaredNums = [ num**2 for num in nums ]
print(nums)
Dictionary Comprehension
# creating a dictionary of even numbers and square values using
comprehension

numbers = [ x for x in range(10) ]


squares = { num : num**2 for num in numbers if num % 2 == 0 }
print(squares)

Output
{0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Exercises
• Question 1:
• Using list comprehension, convert the following list to
Fahrenheit. Currently, the degrees are in Celsius
temperatures. The conversion formula is “(9/5) * c + 32”.
• degreesInCelsius = [ 12, 21, 15, 32 ]
• The output should be [53.6, 69.8, 59.0, 89.6]
• Question 2:
• Ask the user to input a single integer up to and including
100. Generate a list of numbers that are exactly divisible by
that number up to and including 100 using list
comprehension. For example, if the number 25 was input,
then the output should be [ 25, 50, 75, 100 ].
Lambda Functions
• Lambda functions also known as anonymous functions, are one-line
functions within Python. Like list comprehension, lambda functions allow
us to reduce the lines of code.
• Syntax,
• lambda arguments : expression
• lambda arguments : returnValue if condition else returnValue

# nd the number of digits of an integer


num = 12345

def ndDigits(x):
return len(str(x))

digits = ndDigits(num)
print(digits)

# use lambda syntax


digits = (lambda x : len(str(x)))(num)
print(digits)
fi
fi
fi
More Lambda Examples
# nd all the even numbers from 0 up to and including a speci ed number
def getEvenNumbers(num):
nums = []
for x in range(num+1):
if x % 2 == 0:
[Link](x)
return nums

evenNums = getEvenNumbers(20)
print(evenNums)

# use lambda and comprehension list syntax


evenNums = (lambda num : [x for x in range(num+1) if x % 2 == 0])(20)
print(evenNums)

# nd the sum of two numbers


x = 10
y = 20
sum = (lambda a, b : a + b)(x, y)
print(sum)

# nd the bigger number using lambda syntax


max = (lambda x, y : x if x > y else y)(8, 20)
print(max)
fi
fi
fi
fi
Exercises
• Question 3:
• Write a lambda function to nd the numbers in the list of
integers are divisible by 5
• For example,
• If the list has these numbers [2, 4, 5, 10, 12, 15, 30]
• Then, the function will return [5, 10, 15, 30]
• Question 4:
• Write a lambda function that takes in a degree value in
Celsius and returns the degree converted into Fahrenheit.
The conversion formula is “(9/5) * c + 32”
fi
The Map, Filter, and Reduce Function

• The map(fun, iter) method is used to iterate over a given


iterable object passed in as “iter” and apply the given
function passed in as “fun” to each item in the iterable object.

• The lter(fun, seq) method lters the given sequence as “seq”


with the help of a function passed in as “fun” that tests each
element in the sequence passed in as “seq” to be true or not.
Therefore, it lters out data that doesn’t meet a condition.

• The reduce(fun,seq) function is used to apply a particular


function passed in as “fun” to all of the list elements passed
in as “seq”.This function is de ned in “functools” module.
fi
fi
fi
fi
Examples of map()
# double each number in the list
nums = [2, 4, 6, 8, 10]

def doubleIt(x):
return x * 2

nums2 = list(map(doubleIt, nums))


print(nums2)

# use map() to double each number in the list with lambda function
nums2 = list(map(lambda x : x * 2, nums))
print(nums2)

# use map() to nd the string length for each string in a list


lens = list(map(lambda x : len(x), ["apple", "orange", "pear", "banana"]))
print(lens)
fi
Examples of lter()

# use lter() to nd the students who have the score higher than 95
students = [ {"name": "Peter", "score": 99},
{"name": "Lily", "score": 78},
{"name": "Tom", "score": 100}]

goodStudents = list( lter(lambda x : x['score'] > 95, students))

print(goodStudents)
fi
fi
fi
fi
Examples of reduce()
from functools import reduce

# nd reduce() to nd the sum of all numbers in a list


nums = [2, 4, 6, 8, 10]
sum = reduce(lambda sum, x: sum + x, nums)
print(sum)

# nd reduce() to nd the largest number in a list


nums = [12, 4, 6, 18, 10]
max = reduce(lambda max, x: max if max > x else x, nums)
print(max)

# nd reduce() to nd the smallest number in a list


nums = [12, 4, 6, 18, 10]
min = reduce(lambda min, x: min if min < x else x, nums)
print(min)
fi
fi
fi
fi
fi
fi
Exercises
• Question 5:
• Use map() to trim leading and trailing spaces of each name in the list
• For example,
• If the list has these names: [" Peter", " Nancy ", "Paul ", " Thomas "]
• Then, the result will be ['Peter', 'Nancy', 'Paul', 'Thomas']
• Question 6:
• Use lter() to lter out all the names started with P in the list
• For example,
• If the list has these names: ['Peter', 'Nancy', 'Paul', 'Thomas']
• Then, the result will be ['Peter', 'Paul']
• Question 7:
• Use reduce() to reduce() to concatenate strings and also capitalize the rst
letter of each string in a list.
• For example,
• If the list has these strings: ["apple", "orange", "pear", "banana"]
• Then, the resulting string will be “Apple, Orange, Pear, Banana”
fi
fi
fi

You might also like