PyData Careers
20.9K subscribers
206 photos
4 videos
26 files
352 links
Python Data Science jobs, interview tips, and career insights for aspiring professionals.

Admin: @HusseinSheikho || @Hussein_Sheikho
Download Telegram
🐍 Python Tip: Loop with Index using enumerate! 🐍

When you need to iterate through a sequence and also need the index of each item, enumerate() is your best friend! It's more "Pythonic" and cleaner than manually tracking an index.

enumerate() adds a counter to an iterable and returns it as an enumerate object. You can then unpack it directly in your for loop.

my_fruits = ["apple", "banana", "cherry", "date"]

Using enumerate() for a clean loop with index

print("--- Looping with default index ---")
for index, fruit in enumerate(my_fruits):
print(f"Fruit at index {index}: {fruit}")

You can also specify a starting index for the counter

print("\n--- Looping with custom start index (e.g., from 1) ---")
for count, fruit in enumerate(my_fruits, start=1):
print(f"Fruit number {count}: {fruit}")


Output:
--- Looping with default index ---
Fruit at index 0: apple
Fruit at index 1: banana
Fruit at index 2: cherry
Fruit at index 3: date

--- Looping with custom start index (e.g., from 1) ---
Fruit number 1: apple
Fruit number 2: banana
Fruit number 3: cherry
Fruit number 4: date


enumerate() makes your loops more readable and prevents common indexing errors. Give it a try!

#PythonTips #PythonProgramming #LearnPython #Enumerate #CodingHacks

---
By: @DataScienceQ
Python Tip: Mastering init and self in OOP! 🐍

When defining a class in Python, init is a special method (often called the constructor) that gets called automatically every time a new object (instance) of the class is created. It's used to set up the initial state or attributes of that object.

The self parameter is a convention and the first parameter of any instance method. It always refers to the instance of the class itself, allowing you to access its attributes and other methods from within the class.

class Car:
def init(self, make, model, year):
self.make = make # Assign 'make' to the instance's 'make' attribute
self.model = model # Assign 'model' to the instance's 'model' attribute
self.year = year # Assign 'year' to the instance's 'year' attribute

def get_description(self):
return f"This is a {self.year} {self.make} {self.model}."


In the init method, self.make = make means "take the value passed in as make and assign it to the make attribute of this specific Car object."

Let's create some cars:
my_car = Car("Toyota", "Camry", 2020)
your_car = Car("Honda", "Civic", 2022)

print(my_car.get_description())
print(your_car.get_description())


Output:
This is a 2020 Toyota Camry.
This is a 2022 Honda Civic.


init ensures each object starts with its own data, and self connects you to that data!

#PythonTip #OOP #Classes #InitMethod #SelfKeyword #ObjectOriented #PythonProgramming
---
By: @DataScienceQ