Friday 6 September 2024

4 Python Power Moves to Impress Your Colleagues

 

1. Use List Comprehensions for Cleaner Code

List comprehensions are a compact way to generate lists from existing lists or other iterable objects. They are often faster and more readable than traditional for loops.


# Traditional for loop approach

squares = []

for i in range(10):

    squares.append(i**2)


# List comprehension approach

squares = [i**2 for i in range(10)]



2. Use the zip() Function for Iterating Over Multiple Lists

The zip() function allows you to combine multiple iterables and iterate through them in parallel. This is useful when you need to handle multiple lists in a single loop.


names = ['Alice', 'Bob', 'Charlie']

scores = [85, 90, 95]


for name, score in zip(names, scores):

    print(f'{name}: {score}')

Alice: 85

Bob: 90

Charlie: 95



3. Use enumerate() for Indexed Loops

Instead of manually managing an index variable while iterating, you can use the enumerate() function, which provides both the index and the value from an iterable.


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


# Without enumerate

for i in range(len(fruits)):

    print(i, fruits[i])


# With enumerate

for i, fruit in enumerate(fruits):

    print(i, fruit)

0 apple

1 banana

2 cherry

0 apple

1 banana

2 cherry




4. Use Unpacking for Cleaner Variable Assignment

Python supports unpacking, which allows you to assign multiple variables in a single line. This is particularly useful when working with tuples or lists.


# Unpacking a tuple

point = (3, 5)

x, y = point

print(f'X: {x}, Y: {y}')


# Unpacking with a star operator

a, *b, c = [1, 2, 3, 4, 5]

print(a, b, c)  

X: 3, Y: 5

1 [2, 3, 4] 5

0 Comments:

Post a Comment

Popular Posts

Categories

AI (29) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (122) C (77) C# (12) C++ (82) Course (67) Coursera (195) Cybersecurity (24) data management (11) Data Science (100) Data Strucures (7) Deep Learning (11) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (837) Python Coding Challenge (279) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (41) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses