PYTHON JOURNEY - Day 36 / 50..!! TOPIC – Python Tuples Today I explored Tuples — the "reliable cousin" of the list. While they look similar, they have one major difference that makes them special! 1. Creating a Tuple Tuples use parentheses () instead of square brackets. Python coordinates = (10.5, 20.0) colors = ("Red", "Green", "Blue") print(colors) 2. The Golden Rule: Immutability Once a tuple is created, you cannot change, add, or remove its items. This makes them "read-only." Python # This will cause an ERROR: # colors[0] = "Yellow" 3. Packing and Unpacking A cool Python feature where you can assign tuple values to multiple variables at once! Python point = (5, 10) x, y = point # Unpacking print(f"X: {x}, Y: {y}") Why Use Tuples? Safety: Use them for data that should never change (like GPS coordinates or constants). Speed: Tuples are slightly faster than lists in terms of performance. Integrity: Prevents accidental data modification in larger programs. Mini Task Write a program that: Creates a tuple containing the name of a country and its capital city. Try to change the capital city and observe the TypeError. Unpack the tuple into two variables: country and capital, and print them. #Python #PythonLearning #50DaysOfPython #DailyCoding #LearnPython #CodingJourney #PythonForBeginners #LinkedInLearning #DeveloperCommunity
Python Tuples: Immutable Data Structures for Safety and Speed
More Relevant Posts
-
🐍 Python Challenge: The Classic Mutable Default Argument Trap! This is perhaps one of the most infamous "gotchas" in Python Interview questions. It catches beginners and even experienced developers off guard if they aren't paying close attention to how Python handles memory. Take a look at the function definition in the image. We are calling f(1) followed immediately by f(2). What exactly will be printed to the console? 💡 The Answer & Explanation: The actual output is: ---------------- [1] [1, 2] ---------------- Why does this happen? Why isn't the second output just [2]? The secret lies in when Python evaluates default arguments. Default parameter values (like l=[ ] in the image) are evaluated only once when the function definition (def f...) is executed, not every time the function is called. Because a list ([ ]) is a mutable object, Python creates one list object in memory when the function is defined. If you don't provide a value for l, Python reuses that exact same list object for every subsequent call. 1. Call f(1): It uses the default empty list created at definition time. It appends 1. The default list object in memory is now [1]. 2. Call f(2): It uses the same default list object (which now contains [1]). It appends 2. The list becomes [1, 2]. How to fix it in real code? Use None as the default and initialize inside the function: def f(x, l=None): if l is None: l = [ ] ... Did you spot the trap immediately, or did you fall for it? Be honest in the comments! 👇 #Python #Programming #SoftwareEngineering #CodingChallenge #PythonDeveloper #TechTips #DigitalFinancialServices #BackendDevelopment
To view or add a comment, sign in
-
-
More fun with dark corners of Python (yeah, this language is so easy to learn). Consider the following function: >>> def f(x): ... if x == 42: ... return x ... else: ... yield from([x]) When you call it with an argument not equal to 42, this is a generator alright: >>> list(f(1)) [1] Here f yielding from list [x] for x equal to 1, so no big surprise in the answer. But: >>> list(f(42)) [] Where is my number? Why don't I get syntax error? (Try list(42).) The reason is as following: - "yield from" tells Python that "f" is a generator - Python documentation says that "return val" in a generator is equivalent to "raise StopIteration(val)". And indeed: >>> try: ... next(f(42)) ... except StopIteration as ex: ... print(ex.value) ... 42 Here is my 42. #python #gotcha
To view or add a comment, sign in
-
If Python is a "memory managed" language, but who is managing it? Reference Counter! Reference counter is what decides exactly when an object lives and when it dies in python. As discussed in previous posts, every object in Python carries a hidden counter. This counter tracks exactly how many variables are currently pointing to it. How it works? 1. Assignments: When we do y = x, Python finds the object x is pointing to and increments its counter (+1). 2. Deletions: When we do del x, Python finds the object x is pointing to and decrements its counter (-1). 3. Scope Exit: When a function finishes, all variables inside that function disappear. Python automatically decrements the counter of the objects they pointed to (-1). The moment that counter hits 0, Python immediately deletes the object and frees the memory. While this system is fast, it isn't "thread-safe". If two threads try to update the counter at the exact same time, the tally can get corrupted. That is exactly the reason, Python has Global Interpreter Lock(GIL) in place. Will discuss about it in more detail in next post. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
In Python, variables are not just a "box" where we store data. In C or C++, a variable is a memory location. When we change the value, we overwrite what is inside that specific "box". In Python, variables are just tags (pointers) stuck onto an object. And everything in Python is object, as I mentioned in last post. How it works? Imagine a balloon floating in a room as an object. A variable is simply a string tied to that balloon. 1. a = [1, 2, 3] -> We create a balloon and tie a string labeled "a" to it. 2. b = a -> We don’t create a new balloon. We just tie a second string labeled "b" to the exact same balloon. 3. a.append(4) -> We changed the balloon. Since "b" is tied to the same balloon, b now also "sees" the change. Why does it matter? This is where Reference Counting gets its name. Python doesn't count how many "boxes" you have. It counts how many strings are currently tied to the balloon. -> Tie a string? Refcount +1 -> Untie a string (del a)? Refcount -1 Being careful while passing variables(objects) inside functions in python is necessary for this reason. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
-
String Formatting in Python: F-Strings vs. Format Method String formatting is essential when you need to generate dynamic messages or output, especially in applications that handle variable user input. Python provides multiple ways to format strings, but the two most common methods are f-strings and the `format()` method. F-strings, introduced in Python 3.6, allow you to embed expressions directly within string literals. This means you can utilize variables and even expressions inside curly braces. For example, the expression `f"My name is {name} and I am {age} years old."` illustrates how user-friendly it is to create personalized messages. The key advantage of f-strings is not only their clarity but also their readability, as they visually connect the message content with the variables that define them. Conversely, the `format()` method offers more flexibility, particularly for earlier Python versions. This method uses placeholders in the string, such as `"My name is {} and I am {} years old.".format(name, age)`. With this approach, you can rearrange the order of the placeholders or even assign names for clarity. However, this can sometimes feel less intuitive than f-strings, especially when you're dealing with multiple variables. Mastering these string formatting techniques is vital, as they enhance your code's clarity and maintainability. Selecting the right method can save frustration when you are updating messages or debugging your code. Quick challenge: How would you modify the f-string to include an additional variable for a hobby, such as "hiking"? #WhatImReadingToday #Python #PythonProgramming #StringFormatting #LearnPython #Programming
To view or add a comment, sign in
-
-
Power of Generators in Python:- When dealing with large datasets, logs, or streams, loading everything into memory is expensive and slow. Generators solve this by producing values on demand, one at a time, as you iterate. 🔹 Real definition (Generators in Python):- A generator in Python is a function or expression that returns an iterator and yields values one-by-one using the yield keyword instead of return. The code inside a generator pauses at each yield, remembers its state, and resumes from there when the next value is requested (for example, in a for loop or with next()). >>Image explanation (for your graphic):- Design a simple, clear image that explains generators visually: >>Visual idea: >Show a water tap connected to a big water tank labeled “data”. >Water drops coming out one-by-one from the tap are labeled yield value, and the whole tap is labeled “generator function”. >>Concept on the image: >Tank = all possible data >Tap = generator (controls flow) >Drops = values produced lazily, only when needed >>Caption text on image: “Generators in Python: produce one value at a time using yield, saving memory and improving performance.” You can add a small code snippet on the side of the image: def gen(): for i in range(5): yield i >>Key advantages of generators:- >Memory efficient: No need to store the entire sequence in memory; values are generated on-the-fly, which is ideal for large files, logs, or big ranges. >Lazy evaluation: Values are computed only when requested, reducing unnecessary work and improving performance. >Easy to write iterators: Generators create iterators without writing __iter__() and __next__() manually, making code cleaner and more Pythonic. >Great for pipelines: Multiple generators can be chained to build efficient data-processing pipelines step by step (filtering, transforming, mapping, etc.). #Python #Generators #PythonTips #PythonDeveloper #Programming #Coding #SoftwareDevelopment #LearnPython #DataProcessing #CleanCode
To view or add a comment, sign in
-
-
Basic String Operations with Python In Python, strings are immutable sequences of characters, which means once a string is created, it cannot be changed. This characteristic may seem limiting at first, but it leads to safer and more efficient code. You can easily access individual characters in a string using indexing, where Python treats the first character as index `0`. Negative indexing allows access to characters from the end of the string—so, for example, `greeting[-1]` gives you the last character. Slicing also comes into play; the expression `greeting[7:12]` extracts the substring "World". Python provides a variety of built-in methods for string manipulation. For instance, the `upper()` method converts the entire string to uppercase, while the `replace()` method can substitute specific parts of the string with other text. Importantly, these methods return new strings, meaning your original string remains unchanged. Mastering string operations is essential in real-world applications such as web development, data analysis, and automation scripts. Understanding these fundamental operations enhances your ability to interact with text data and fosters more robust programming practices. Quick challenge: How can you use negative indexing to extract the last 5 characters of the string? #WhatImReadingToday #Python #PythonProgramming #Strings #PythonTips #Programming
To view or add a comment, sign in
-
-
In this session I learned about the topic is functions of python: *Functions of python: A function is a block of reusable code that performs a specific task.It help make programs modular, readable, and reusable. #Types functions of Python : 1. Built-in Functions: These are predefined functions available in Python. #Examples: print() input() len() type() range() 2. User-Defined Functions: Functions created by the programmer using the def keyword. #Syntax: Python def function_name(): statements #Example: Python def greet(): print("Hello") 3. Functions with Parameters: Functions that accept input values. #Example: Python def add(a, b): print(a + b) 4. Functions with Return Value: Functions that return a result using the return statement. #Example: Copy code Python def square(x): return x * x 5. Lambda Functions: Small anonymous functions written in one line. #Example: Copy code Python square = lambda x: x * x 6.Recursive Function: A recursive function is a function that calls itself to solve a problem by breaking it into smaller sub-problems. #General Syntax: Copy code Python def function_name(): if base_condition: return value else: return function_name(smaller_input). Lakshmi Tejaswi Akula, Ayesha parvin, Athota Amulya,Kadiyam Akanksha, AMULYA DOMA, Lakshmi Tirupatamma , Gunturu Sony, Thanuja Karnati, Konduru sai mounika,Ashok raj Sagana boyana, Rakshandhaa Syed , Chandu Sri Kavya, Polu chandana sri, Jyothika Namburu, Jhansi lakshmi Gopisetti, Veerla Meenakshi, Deevena Florence. Vemuru, vanikumari Buragadda, Sravani Chillara, Sravanthi Katta, Kakumanu Baby Honey , Golla Gayathri , NIKHITHA REPALLE, Nandini Kona,Mikkilineni Bhavana ,Madhavi Posam ,Mudigonda mukhesh,Supriya Nadakuduru,Sharon Samudrala ,Srinivas Yarlagadda, Shaik Afthaf, SHAIK BAJI, Srikar GCV (Trainer)
To view or add a comment, sign in
-
Mastering Iterators in Python:- When you loop over a list, string, or file in Python using a for loop, you are already using iterators behind the scenes. Understanding them gives you more control over data processing, especially with large datasets and streams. 🔹 Real definition (Iterator in Python):- An iterator in Python is an object that returns the next item from a sequence each time you call next() on it, following the iterator protocol with __iter__() and __next__() methods. You usually get an iterator by passing an iterable (like a list, tuple, or string) to the built-in iter() function, and a for loop automatically uses this iterator internally >>Image explanation :- Use a simple, clean image that explains the concept visually: >Visual idea: Show a conveyor belt with boxes (elements: 10, 20, 30, 40) moving one-by-one to a worker labeled iterator, and behind the belt a warehouse labeled list. >Concept to highlight in text on the image:- >>Warehouse = iterable (stores all items) >>Conveyor belt worker = iterator (gives one item at a time using next()) >Caption on image: >> Iterator in Python: get one item at a time from an iterable, instead of loading everything at once. >Key advantages of iterators:- >>Memory efficient: Process one element at a time without storing the whole sequence in memory, ideal for large or infinite data streams. >>Lazy evaluation: Values are produced only when needed, which reduces unnecessary computation and speeds up pipelines. >>Clean and uniform looping: The same for loop syntax works across lists, tuples, strings, files, and custom objects via iterators. >>Powerful with generators and itertools: Iterators combine with generators to build flexible, composable data-processing pipelines. #Python #Iterators #PythonTips #PythonDeveloper #Programming #Coding #SoftwareDevelopment #LearnPython #DataProcessing #CleanCode
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