Crucial Python Concepts

1. Underscore

In the interactive shell, the underscore stores the value of the previously evaluated expression.

(Using underscore as an anonymous variable that I don’t have to access or utilize)

data = [(1, 'one'), (2, 'two'), (3, 'three')]
for _, word in data:
 print(word)
(Deploying private members in classes)
class Person:
 def __int__(self) -> None:
 self._name = "Tim"
  1. Lambda Function:

    One-liner anonymous functions are extremely useful in callbacks. Lamda is often used in map and filter functions.

people = [
 {“name”: “Alice”, “age”: 25},
 {“name”: “Bob”, “age”: 20},
 {“name”: “Josh”, “age”: 22},

]

# Use lambda to sort the list of dictionaries by ‘age’ field
people.sort(key=Lambda person: person[‘age’])

for person in people:
 print(f”{person[‘name’]}: {person[‘age’]}”)

def call(func):
 func()

def add(x , y):
 return x + y

call(Lamda: add(2, 3) //Wrapping this function call
  1. Zip Function:

    Matching indices. Returns a tuple that contains all of the matching indices in that tuple.
    Note: Zip goes only as far as the shortest list or the shortest Iterable object

students = [“Alice”, “Bob”, “Charlie”, “David”]
grades = [85, 90, 78, 92]
//color = [“blue”, “red”] (Example)

#Use zip to create pairs of student and grade
for students, grade in zip(students, grades):
 print(f”{student}: {grade}”)

print(list(zip(students, grades)))

4) .GET() Function:

Access value associated with a key from a dictionary

words = [‘apple’, ‘banana’, ‘mango’]
word_counts = {}

for word in words:
//If the word is already a key in the dictionary, get() returns its current count;
//If the word is not yet a key, get() returns the default value oof 0.
 word_counts[word] = word_counts.get(word, 0) + 1

print(word_counts)

5. setdefault()

# Create a dictionary to store student grades for different subjects

student_grades = {}

#Try to add a grade for ‘math’ for a student names ‘Alice’ using .get()
math_grades = student_grades.get(‘Alice’, {})
math_grades[‘math’] = 90
print(student_grades) # prints: {}

# Now try to add a grade for ‘english’ for ‘Alice’ using .setdeault()

english_grades = student_grades.setdefault(‘Alice’, {})
english_grades[‘english’] = 85
print(student_grades) # prints: {‘Alice’: {‘english’: 85}}

5 Tips To Organize Python Code

1. Use Modules and Packages
2. One Class = One File
3. Group-Related Functionality Together
4. Separate Utility & Helper Functions
5. Organize Imports

Python Mistakes:

  1. Name Shadowing

  2. Mutuable Default Parameters

  3. Name Clashing

  4. Naked Except

  5. Wrong DS

  6. Global variables

A valuable resource: https://www.python-engineer.com/newsletter/

Conclusion:

I will include more of my Python Learnings such as Comprehensions which is a separate topic itself.

If you found this post useful, give it a like👍

Follow Nishi Tiwari for more such posts 💯🚀