Python Pioneers: A Beginner's Guide 🇪🇹
8.83K subscribers
346 photos
40 videos
24 files
64 links
Welcome to Python Pioneers: Empowering Ethiopian students to embark on their coding journey.

📢 Channel: @python_pioneers
👥 Group: @python_pioneers_chat
Download Telegram
List comprehensions
List comprehensions are expressions that allow us to transform lists in a single line. The syntax:
[ <inner_expression> for <item> in <list> ]


It may look intimidating at first glance but what will happen is python loops through the list and executes the <inner_expression> for each <item> in <list> to create a new list.

# Example
nums = [1, 2, 3, 4, 5]
squared = [n ** 2 for n in nums]
print(squared)

# output: [1, 4, 9, 16, 25]


Above we have two expression the outer_expression which is the list comprehension itself and the inner_expression (n ** 2) which transforms the list. In this case the inner_expression squares each item from the list.

#PythonTips #GettingToKnowPython #PythonPatterns
❤1
Lambda functions
Another cool expressions or patterns in python are lambda functions a.k.a anonymous functions. We use them to define functions inline (in one line).
# Syntax
lambda arguments: expresion

The subtle thing we need to understand about anonymous funtions/lambda functions is that they don't have a name unless we explicitly assign them to a variable. The return value of lambda function is the evaluated expression.

The concept actually exists in many programming languages as anonymous functions or function expression, even-though the syntax could be different.
# Examples

# This is valid - With no name
lambda x: x

# With a name
times2 = lambda x: x * 2

# With two argumetns
prefix = lambda pre, post: pre + post;
postfix = lambda post, pre: prefix(pre, post)

print(times2(10))
print(prefix("main", ".py"))
print(postfix(".py", "main"))

# ----------Output----------
20
main.py
main.py


#LambdaFunctions #PythonProgramming #PythonTips #GettingToKnowPython
❤1