🚀 Day 6 of my 30 Days Python Challenge: Mastering Python starts with mastering lists! Here’s your ready reckoner with real code + outputs and use cases—just for you! A Python list is an ordered, dynamic, and mutable collection that can hold any type of data—like numbers, strings, or even other lists. 💡 Why use lists? Flexible for all data types Store, access, edit, or remove elements easily Used everywhere—from automation to data science! 🎯 Let’s see real list magic in Python: # 1️⃣ Create & check type my_list = [1, 2, 3, 4, 5] print(type(my_list)) # Output: <class 'list'> ###################################### # 2️⃣ List with multiple data types mixed = [10, "Krishna", 2.5, True] print(mixed) # Output: [10, 'Krishna', 2.5, True] ###################################### # 3️⃣ Access by index fruits = ['Apple', 'Banana', 'Mango'] print(fruits[0]) # Output: Apple print(fruits[2]) # Output: Mango ###################################### # 4️⃣ Slicing numbers = [1, 2, 3, 4, 5] print(numbers[1:4]) # Output: [2, 3, 4] ###################################### # 5️⃣ Change value numbers = [10, 20, 30, 40] numbers[2] = 99 print(numbers) # Output: [10, 20, 99, 40] ###################################### # 6️⃣ Add elements (append, insert, extend) nums = [1, 2, 3] nums.append(4) print(nums) # Output: [1, 2, 3, 4] nums.insert(1, 99) print(nums) # Output: [1, 99, 2, 3, 4] nums.extend([7, 8]) print(nums) # Output: [1, 99, 2, 3, 4, 7, 8] ###################################### # 7️⃣ Remove element (pop) colors = ['red', 'green', 'blue'] removed = colors.pop() print(removed) # Output: blue print(colors) # Output: ['red', 'green'] ###################################### # 8️⃣ Nested lists matrix = [ [1, 2, 3], [4, 5, 6] ] print(matrix[1][2]) # Output: 6 ###################################### # 9️⃣ List functions (len, max, min) data = [7, 12, 4, 9, 21] print(len(data)) # Output: 5 print(max(data)) # Output: 21 print(min(data)) # Output: 4 ###################################### # 🔟 Methods (reverse, copy, count) nums = [5, 2, 5, 7] nums.reverse() print(nums) # Output: [7, 5, 2, 5] copy_nums = nums.copy() print(copy_nums) # Output: [7, 5, 2, 5] print(nums.count(5)) # Output: 2 ###################################### 🔥 Real-world uses: Data science: holding survey results, experiment values Web: lists of products, users ML/AI: feature sets, predictions Automation: batch rename, organize files and folders ❓ Your turn: What’s the most creative way you used a Python list? Share your favorite tip, question, or challenge below 👇 Want more Python details? Comment "YES" & save this post! #Python #DevOps #LearnPython #CodingTips #Automation #DataScience #AIBasics #Programming #LinkedInLearning Follow for more actionable DevOps and Python tips with real-world examples!
Mastering Python Lists: A Ready Reckoner
More Relevant Posts
-
🐍 Python Variables — The Foundation of Every Program! When you code in Python, you’ll constantly deal with variables — they’re the containers that hold your data. Think of a variable as a label you stick on a box — the box can contain numbers, text, or anything else! 📦 🔹 What is a Variable? A variable is used to store data in memory so you can use it later in your program. 🧩 Example: name = "Arun" age = 28 height = 5.9 Here, name holds a string ("Arun") age holds an integer (28) height holds a float (5.9) 🔹 Why We Use Variables ✅ To store data temporarily ✅ To manipulate and reuse values easily ✅ To make code more readable and dynamic Imagine having to rewrite a value 100 times — with variables, you just change it once! 💡 🔹 Variable Naming Rules Python variable names follow simple but strict rules: ✅ Must start with a letter or underscore (_) ❌ Cannot start with a number ✅ Can contain letters, digits, or underscores ✅ Are case-sensitive (Name ≠ name) 🧠 Examples: user_name = "John" UserName = "Jane" # Different variable _age = 25 🔹 Dynamic Typing in Python Python is dynamically typed, meaning you don’t need to declare the data type. It detects it automatically! 🪄 x = 10 # int x = "Hello" # now string Same variable — different data types, and Python handles it smoothly! 🔹 Multiple Assignments You can assign multiple values in one line: a, b, c = 10, 20, 30 Or assign one value to many variables: x = y = z = 100 🔹 Variable Types A variable can hold: Numbers → int, float, complex Text → str True/False → bool Collections → list, tuple, set, dict Use type() to check what kind of data your variable holds: a = "Python" print(type(a)) # <class 'str'> 💡 Quick Recap ✅ Variables are containers for data ✅ No need to declare types manually ✅ Follow simple naming rules ✅ Use type() to check variable types 🚀 Pro Tip Use meaningful names — Instead of: x = 100 Use: marks = 100 It makes your code self-explanatory and professional. 🧠 #Python #Coding #Learning #Programming #DataScience #LinkedInLearning #Tech #CupuleChicago #analyticssolution #cupulegwalior #cupuleeducation
To view or add a comment, sign in
-
As data volumes grow, efficiency in data processing becomes critical. Our latest blog explores whether Polars could be the next big step beyond Pandas for Python developers and data scientists. Read the full insight here: https://lnkd.in/g38X4uS9 #DataScience #Python #PolarsvsPandas #polarspythonlibrary #pandasinpython #DataMites
To view or add a comment, sign in
-
🚀 Day 7 of #100DaysOfDataEngineering Topic: Python Advance - NumPy Basics Tags: #Python #NumPy #DataEngineering #DataScience Today marks the start of our journey into Python for numerical computing. Meet NumPy (Numerical Python), the core library that powers data transformations, mathematical operations, and many popular tools like Pandas and Scikit-learn. 💡 What is NumPy? NumPy provides multi-dimensional arrays (ndarray) and efficient functions to work with them. It is built for speed, allowing you to process large datasets much faster than standard Python lists. Install NumPy with: pip install numpy Import the library: import numpy as np 🧱 Creating Arrays You can create NumPy arrays directly from Python lists or nested lists: import numpy as np # 1D array arr1 = np.array([10, 20, 30]) # 2D array arr2 = np.array([[5, 10, 15], [20, 25, 30]]) print(arr1.shape) # (3,) print(arr2.shape) # (2, 3) print(arr1.dtype) # int64 ⚙️ Common Attributes AttributeDescriptionndarray.shapeDimensions of the array (rows, columns)ndarray.dtypeType of data stored (int, float, etc.)ndarray.ndimNumber of dimensionsndarray.reshape()Change array shape without changing data 📊 Built-in Methods NumPy includes several helpful functions for creating arrays quickly: # Evenly spaced values (like range) np.arange(0, 10, 2) # [0 2 4 6 8] # Arrays of zeros and ones np.zeros((2, 3)) # 2x3 array of zeros np.ones((3, 2)) # 3x2 array of ones # Equally spaced numbers np.linspace(0, 10, 5) # [0. 2.5 5. 7.5 10.] 🎲 Generating Random Numbers NumPy makes it simple to generate test data for experiments and simulations: # Random values (uniform distribution) np.random.rand(3, 4) # Random values (normal distribution) np.random.randn(2, 3) # Random integers between 4 and 40 np.random.randint(4, 40, 10) # 4x4 matrix of random integers up to 50 np.random.randint(50, size=(4,4)) ✅ Key Takeaway NumPy is all about speed and simplicity. It lets you handle large datasets and perform calculations efficiently. These array operations form the foundation of every scalable data pipeline.
To view or add a comment, sign in
-
🧮 Dissecting NumPy: Working With Intrinsic NumPy Objects For Array Creation 💪 It feels really exciting getting into the core of NumPy and seeing it unlocking its true strength infront of me! 🤔 Why NumPy Arrays Are Better Than Python Lists? - Fast Computation Of Large Datasets - Dont Require Loops - Easy Arithmetical Operations - Consume Less Memory ⚙️Today i digged a bit deeper into NumPy Array Creation With Intrinsic Objects like: - np.ones/np.zeros: gives arrays of 1s and 0s - np.arange(): gives a sequence of array unlike python range() that gives integers - np.linspace(): gives equally linear numbers in array between a start and stop value - np.reshape(): it can simply reshape a given array without changing its data, means generates a new array with a different number of rows and columns (as specified) But, listen up! ‼️One critical thing about NumPy Arrays is their Axis0(rows) and Axis1(coulums). ‼️It means we can perform some of the arithmetical ops on row elements and colum elements using their axis 💭 Its been a productive week by far getting into the world of NumPy and unlocking a new skill on the way of becoming a data scientist! 🫡 Until we meet again, my fellow coders! ------------------------- ☺️ Here are Python (Beginner to Intermediate) GitHub Repos for you: 📁Python Variables: https://lnkd.in/e9rjz-_D 📁Python Operators: https://lnkd.in/e6hzgHSn 📁Python Conditionals: https://lnkd.in/egQNGZBF 📁Python Loops: https://lnkd.in/eezUg_-y 📁Python Functions: https://lnkd.in/eKdU6nex 📁Python Lists & Tuples: https://lnkd.in/eZ8KiQNs 📁Python Dictionaries & Sets: https://lnkd.in/eDmgj7pc 📁Python OOP: https://lnkd.in/eJFupCiK 📁Python DSAs: https://lnkd.in/ebR3rjkt ------------------------- 🤓 NumPy (Beginner To Intermediate): 🧮Arrays: https://lnkd.in/ebghYRYE ------------------------- ⚡ Follow my learning journey: 📎 GitHub: https://lnkd.in/ehu8wX85 🔗 GitLab: https://lnkd.in/eiiQP2gw 💬 Feedback: I’d love your thoughts and tips! 🤝 Collab: If you’re also exploring Python, DM me! Let’s grow together! -------------------------- 📞Book A Call With Me: https://lnkd.in/e23BtnR9 -------------------------- #pythonnumpy #NumPy #pythonlibraries #pythonfordatascience #datascience #machinelearning #artificialintelligence
To view or add a comment, sign in
-
### 🧠 **Day 48 – Python OOPs: Private, Protected, and Class Method Concepts** Today I learned how to use **private and protected variables** in Python classes and how **name mangling** helps access them safely. #### 🧩 **Code Summary** ```python class cl_new: def __init__(self, name, age): self.__name = name # Private variable self._age = age # Protected variable def m_new(self): print(f"name = {self.__name}, age = {self._age}") @classmethod def m_cl_ndth(cls, name, age): return cls(name, age) def m_2(self): self.__m_new() # Call private method internally # Object 1 n = cl_new("siva", 27) n._cl_new__m_new() # Access private method via name mangling print(n._cl_new__name) # Access private variable using mangling print(n._age) # Object 2 n2 = cl_new("krishna", 45) n2.m_new() # Class method usage prxy = cl_new.m_cl_ndth("pawan", 60) prxy.m_new() # Object 3 n3 = cl_new("kalyan", 20) n3.m_new() ``` --- ### 🧾 **Concepts Explained** #### 🔒 1. **Private Variables (`__var`)** * Declared with **double underscores (`__`)**. * Not directly accessible outside the class. * Accessed only using **name mangling** like: ```python object._ClassName__variable ``` * Example: `self.__name` #### 🛡️ 2. **Protected Variables (`_var`)** * Declared with a **single underscore (`_`)**. * Accessible within the class and subclasses, but **should not** be accessed directly from outside (by convention). * Example: `self._age` #### 🧩 3. **Private Methods** * Methods declared with `__` prefix. * Example: `__m_new()` * Can be accessed inside the class or externally using name mangling. #### 🧠 4. **Class Method** * Declared using `@classmethod` decorator. * Takes `cls` as the first parameter. * Used to create new objects using alternative constructors. --- ### 🖥️ **Output Explanation** ``` name = siva, age = 27 name = siva, age = 27 siva 27 name = krishna, age = 45 name = pawan, age = 60 name = kalyan, age = 20 ``` ✅ Demonstrates how to define and access private/protected members. ✅ Shows **class method** usage for creating objects dynamically. ✅ Explains **encapsulation**, one of the main OOPs principles. --- ### 💡 **Key Takeaway** Encapsulation in Python ensures data hiding and protects object integrity. Using **private, protected, and class methods**, we can control access to class data efficiently. --- ✨ Every day brings a deeper understanding of Object-Oriented Programming with Python! #Python #OOPs #Encapsulation #Day48 #LearningJourney #Programming #LinkedInLearning #ClassMethod #PrivateVariables
To view or add a comment, sign in
-
Dictionaries in Python: The Pantry Labels of Your Code 🏷️ Your pantry has so many items — but how do you find things easily? You don’t just dump everything in boxes — you label them! “Sugar → 1kg” “Milk → 2 packets” “Coffee → 500g” That’s what Dictionaries in Python do - they store data as key–value pairs, just like labeled jars in your kitchen! 💡 What is a Dictionary? A dictionary helps you store and access data using names (keys) instead of positions. Think of it like this: Instead of saying “Give me the 3rd item”, you can say “Give me the sugar!” 📘 Example: pantry = { "Sugar": "1kg", "Milk": "2 packets", "Coffee": "500g" } Now, if you want to check what’s in your pantry: print(pantry) Output: {'Sugar': '1kg', 'Milk': '2 packets', 'Coffee': '500g'} 💬 Accessing Items You can get values by using their key names: print(pantry["Sugar"]) Output: 1kg Easy, right? No need to remember the position - just ask for the label! 🧠 Updating or Adding Items Refill something or add new stock: pantry["Sugar"] = "2kg" # update existing pantry["Tea"] = "1 box" # add new print(pantry) Output: {'Sugar': '2kg', 'Milk': '2 packets', 'Coffee': '500g', 'Tea': '1 box'} 💥 Removing Items You can remove an item once it’s finished: del pantry["Coffee"] print(pantry) Output: {'Sugar': '2kg', 'Milk': '2 packets', 'Tea': '1 box'} 💡 Why Dictionaries Are Powerful ✅ Easy to find data using names ✅ Data stays organized and readable ✅ Perfect for real-world applications - like storing user info, product details, etc. 🧠 Today’s takeaway: “Dictionaries are like labeled jars — they help you find exactly what you need without confusion!” 💬 Try this today: Create a dictionary with your favorite fruits and their colors 🍎 Then print each fruit with its color using: for fruit, color in fruits.items(): print(fruit, "is", color) #PythonWithKeshav #LearnPython #PythonBasics #CodingJourney #PythonDictionaries #ProgrammingForBeginners #PythonLearning #CodeSmart #STEMEducation #PythonForAll
To view or add a comment, sign in
-
*Important Python concepts that every beginner should know* *1. Variables & Data Types* 🧠 Variables are like boxes where you store stuff. Python automatically knows the type of data you're working with! name = "Alice" # String age = 25 # Integer height = 5.6 # Float is_student = True # Boolean *2. Conditional Statements* 🔀 Want your program to make decisions? Use if, elif, and else! if age > 18: print("You're an adult!") else: print("You're a kid!") *3. Loops* 🔁 Repeat tasks without writing them 100 times! For loop – Loop over a sequence While loop – Loop until a condition is false for i in range(5): print(i) # 0 to 4 count = 0 while count < 3: print("Hello") count += 1 *4. Functions* ⚙️ Reusable blocks of code. Keeps your program clean and DRY (Don't Repeat Yourself)! def greet(name): print(f"Hello, {name}!") greet("Bob") *5. Lists, Tuples, Dictionaries, Sets* 📦 List: Ordered, changeable Tuple: Ordered, unchangeable Dict: Key-value pairs Set: Unordered, unique items my_list = [1, 2, 3] my_tuple = (4, 5, 6) my_dict = {"name": "Alice", "age": 25} my_set = {1, 2, 3} *6. String Manipulation* ✂️ Work with text like a pro! text = "Python is awesome" print(text.upper()) # PYTHON IS AWESOME print(text.replace("awesome", "cool")) # Python is cool *7. Input from User* ⌨️ Make your programs interactive! name = input("Enter your name: ") print("Hello " + name) *8. Error Handling* ⚠️ Catch mistakes before they crash your program. try: x = 1 / 0 except ZeroDivisionError: print("You can't divide by zero!") *9. File Handling* 📁 Read or write files using Python. with open("notes.txt", "r") as file: content = file.read() print(content) *10. Object-Oriented Programming (OOP)* 🧱 Python lets you model real-world things using classes and objects. class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says woof!") my_dog = Dog("Buddy") my_dog.bark() React if you want me to cover each Python concept in detail. Hope it helps :)
To view or add a comment, sign in
-
#DAY-37 #TOPIC: OOPS concepts in python oops are classified into 4 types: 1.inheritance 2.polymorphism 3.abstraction 4.encapusulation #inheritances: Inheritance means one class (child class) can get the properties and methods of another class (parent class). Example-1: class RBI: #parent cash=100000 @classmethod def available_cash(cls): print("available_cash is",cls.cash) #print("available_cash is",RBI.cash) class SBI(RBI):#child-1 pass class HDFC(RBI):#child-2 cash=50000 @classmethod def new_cash(cls): print("new_cash is",cls.cash+cls.cash) #print("new_cash is",cls.cash+RBI.cash) a=SBI() print(dir(a)) b=HDFC() print(dir(b)) b.available_cash() b.new_cash() #output: ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'available_cash', 'cash'] ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'available_cash', 'cash', 'new_cash'] available_cash is 50000 new_cash is 100000 #Task(Multiple inheritance) class Father: def weight(self): print("weight is 60kgs") class Mother: def height(self): print("height is 5.5 inches") class child: def dob(self): print("just born.....") a=Father() a.weight() b=Mother() b.height() c=child() c.dob() #output: weight is 60kgs height is 5.5 inches just born..... Example-2: class Bus: def seats(self): a = input("Enter total number of seats (e.g. 100): ") print("Total seats:", a) class Women: def seats(self): b = input("Enter number of seats for women (e.g. 50): ") print("Seats for women:", b) class Men(Bus, Women): def seats(self): c = input("Enter number of seats for men: ") print("Seats for men:", c) # Create objects and call methods a = Bus() a.seats() b = Women() b.seats() c = Men() c.seats() #output: Enter total number of seats (e.g. 100): 100 Total seats: 100 Enter number of seats for women (e.g. 50): 50 Seats for women: 50 Enter number of seats for men: 40 Seats for men: 40 Codegnan Pooja Chinthakayala mam Saketh Kallepu sir co-founder Uppugundla Sairam sir -CEO
To view or add a comment, sign in
-
🎬 Episode 5 – Python Data Types: The Language of Automation Here’s a truth no one tells beginners… Your automation script is only as smart as the data you give it. If you don’t understand data types, your script won’t just fail — it will break at the worst possible moment. But don’t worry… after today’s episode, your scripts will understand data just like you do. In Python, Data Types decide what kind of information your script is handling. As a network engineer, you’ll use them every day to store IPs, VLAN IDs, interfaces, credentials, and more. 1. String (str) – Text data Used for device names, IP addresses, usernames device = "Router1" ip = "x.x.x.x" 2. Integer (int) – Whole numbers Used for VLAN IDs, port numbers vlan_id = 10 port_number = 8080 3. Float (float) – Decimal numbers Used for bandwidth, CPU %, latency cpu_usage = 23.5 4. Boolean (bool) – True / False Used for status checks is_active = True 5. List ([]) – Multiple items Used for storing multiple IPs or interfaces interfaces = ["Gig0/0", "Gig0/1", "Gig0/2"] 6. Dictionary ({}) – Key-value data The MOST important for automation device_info = { "hostname": "Switch1", "ip": "x.x.x.x", "username": "admin" } 💥Dictionaries are the heart of network automation — almost every automation tool returns device data in dictionary format. APIs return data in JSON. Python converts it into dictionaries. You're not just learning Python — you're learning to speak the language of modern networks. This is a skill that turns a normal engineer into an automation engineer. This was Episode 5 of 100 Days of Network Automation. Data types are the foundation of every script you’ll write from today forward. Master them — and everything else becomes easier. Next up, in Episode 6: Operators in Python — how Python THINKS and makes decisions. If today’s episode cleared your concepts, drop "Love Python" in the comments. #NetworkAutomation #NetDevOps #AutomationEngineer #LearnAutomation #100DaysOfAutomation #Python #Automation #Coding #CloudComputing #TechSkills #ITCareer #InfrastructureAsCode #DevOps #CCNA #Cisco #NetworkEngineer #SkillUp #ITCommunity
To view or add a comment, sign in
-
-
Proposed #Python Solution: Automated File Organizer One common real-world problem is digital clutter, where files downloaded or created accumulate in a single folder (like 'Downloads' or 'Desktop'), making it difficult to locate specific documents quickly. A short Python script can solve this by automatically organizing files into specific, designated subfolders based on their file extension (e.g., all .pdf files go into a 'PDFs' folder, all .jpg files go into an 'Images' folder). import os import shutil # 1. Define the directory to organize (e.g., your Downloads folder) SOURCE_DIR = "/path/to/your/unorganized/folder" # 2. Define mapping from file extensions to folder names FILE_TYPE_MAPPING = { 'pdf': 'PDFs', 'jpg': 'Images', 'png': 'Images', 'docx': 'Documents', 'xlsx': 'Spreadsheets', 'mp4': 'Videos', 'zip': 'Archives' } def organize_files(directory): for filename in os.listdir(directory): # Skip directories and the script itself if os.path.isdir(os.path.join(directory, filename)) or filename == os.path.basename(__file__): continue # Get the file extension (lowercase) file_ext = filename.split('.')[-1].lower() # Determine the target folder name target_folder_name = FILE_TYPE_MAPPING.get(file_ext, 'Others') # Create the full path for the target folder target_path = os.path.join(directory, target_folder_name) # 3. Create the folder if it doesn't exist if not os.path.exists(target_path): os.makedirs(target_path) # 4. Move the file source_file = os.path.join(directory, filename) destination_file = os.path.join(target_path, filename) # Handle files with the same name (optional: adds a simple rename for safety) if os.path.exists(destination_file): print(f"Skipping duplicate: {filename}") continue shutil.move(source_file, destination_file) print(f"Moved {filename} to {target_folder_name}") # Execute the organization if __name__ == "__main__": print(f"Starting organization in: {SOURCE_DIR}") organize_files(SOURCE_DIR) print("Organization complete!")
To view or add a comment, sign in
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development