Protects against unintended changes
Lightweight
Next let‘s explore mutable lists.
Lists are mutable sequences defined with square brackets:
Here is a function returning a list:
Unlike tuples, you can mutate lists:
Use lists when accumulation and transformation is required.
Good list use cases:
Pros | Cons |
---|---|
Mutable Can append/remove elements Widely compatible data structure | No constant immutability guarantees |
Dictionaries are also mutable, containing unordered key-value pairs:
Here is a function returning a dictionary:
Dicts can mutate as well:
Dictionaries work excellently for associative mappings.
Great dictionary cases:
Pros | Cons |
---|---|
Key-based fast lookups Mutable Flexible schemas | Unordered Hash collisions unlikely but possible |
With essential theory covered, let‘s now discuss order of operations…
When returning multiple composite data structures like nested lists/tuples, order of operations applies:
The inner tuple evaluates first, followed by wrapping in the outer list.
You can also directly nest without temporaries:
This rule extends to arbitrary depth levels:
Order your return value nesting appropriately for the data hierarchies involved.
While Python emphasizes code readability first, performance still matters especially at scale.
Let‘s benchmark our tuple/list/dict options using the timeit module over 1 million operations:
As expected, tuples are the fastest for returning multiple values given their immutable nature and lightweight memory footprint, with lists and dicts incrementally slower.
Ideally optimize for readability first, but switch to tuples should performance emerge as a bottleneck.
When returning complex nested data, watch out for these common mishaps:
1. Breaking immutability
Accidentally mutating tuples when attempting to modify returned data:
Use defensive copying if mutations are needed:
2. Circular references
Dictionaries and lists allows containment cycles:
This can lead to recursion errors:
Watch for circular linkage, especially in nested data.
3. Returning references
When returning containers from functions, returning a reference to the original risks side effects:
Return copies to prevent changes:
Now let‘s discuss ecosystem usage trends…
Based on my analysis across thousands of Python codebases:
Some interesting statistics:
So while lists and dicts have clear utility, tuples surprise through their simplicity and immutability.
When possible, default to tuples for returning multiples unless mutability or key-values are explicitly needed. This aligns with overall community patterns.
We‘ve covered extensive ground on returning multiple values in Python through tuples, lists, and dictionaries – from immutable/mutable tradeoffs to nesting hierarchies and ecosystem statistics.
Here are my key recommendations:
I hope you‘ve learned valuable skills to use tuples, lists, and dicts effectively within your Python code! Let me know if you have any other questions.
Follow me at www.mysite.com for more expert Python tutorials.
Dr. Alex Mitchell is a dedicated coding instructor with a deep passion for teaching and a wealth of experience in computer science education. As a university professor, Dr. Mitchell has played a pivotal role in shaping the coding skills of countless students, helping them navigate the intricate world of programming languages and software development.
Beyond the classroom, Dr. Mitchell is an active contributor to the freeCodeCamp community, where he regularly shares his expertise through tutorials, code examples, and practical insights. His teaching repertoire includes a wide range of languages and frameworks, such as Python, JavaScript, Next.js, and React, which he presents in an accessible and engaging manner.
Dr. Mitchell’s approach to teaching blends academic rigor with real-world applications, ensuring that his students not only understand the theory but also how to apply it effectively. His commitment to education and his ability to simplify complex topics have made him a respected figure in both the university and online learning communities.
401K accounts provide American workers with an invaluable tool to save and invest for retirement in…
Introduction The Two Sum problem is a common coding interview question focused on algorithms and data…
Formatting code blocks properly is an essential skill for any tech writer or developer writing technical…
When I first started learning to code, I made the mistake of trying to figure everything…
Google dorking refers to the practice of using advanced Google search operators to find sensitive information…
Deploying a React single page application using client-side routing can result in frustrating 404 “Page Not…
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Is there a way to specify in return value annotation that a list of float s is output only when the input ids is a list of str s or int s?
One way to do this is by using the @overload decorator to create 2 extra function signatures, one for int | str that returns float and one for list[str] | list[int] that returns list[float] and then have the actual function definition like you have now.
Your get is really two different functions. One converts its argument to a float ; the other uses the first to convert a list of arguments to a list of float s.
You only feel compelled to combine them into a single function (for "convenience") because Python lacks a built-in function that makes gets easy to create on the fly from get .
This is an example of "inversion of control": instead of making get decide what to do based on the type of its argument, you decide which function to call based on the type of the argument.
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
IMAGES
VIDEO
COMMENTS
Assignment (sub-)expressions (x := y) are supported since Python 3.8 (released Oct. 2019), so you can indeed now rewrite your example as lst.append(x := X()).. The proposal, PEP 572, was formally accepted by Guido in July 2018.There had also been earlier proposals for assignment expressions, such as the withdrawn PEP 379.. Recall that until version 3, print was also a statement rather than an ...
185. Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (isBig (y)) as a variable (x) in order to re-use it within the body of the condition: if x := isBig (y): return x. edited Jan 8, 2023 at 14:33. answered Apr 27, 2019 at 15:37.
Python's Assignment Operator: Write Robust Assignments
The Python return Statement: Usage and Best Practices
Let's see a code snippet to understand it better. a = 10. b = 20 # assigning value to variable c based on condition. c = a if a > b else b. print(c) # output: 20. You can see we have conditionally assigned a value to variable c based on the condition a > b. 2. Using if-else statement.
Assignment Expressions: The Walrus Operator
Assignment Operators in Python
Unparenthesized assignment expressions are prohibited for the value of a keyword argument in a call. Example: foo(x = y := f(x)) # INVALID foo(x=(y := f(x))) # Valid, though probably confusing. This rule is included to disallow excessively confusing code, and because parsing keyword arguments is complex enough already.
Multiplication and Assignment Operator. The multiplication and assignment operator multiplies the right-side operand with the left-side operand, and then the result is assigned to the left-hand side operand. Below code is equivalent to: a = a * 2. In [1]: a = 3 a *= 2 print(a) 6.
An assignment expression binds the value result to the return of slow_calculation with i. You add the result to the newly built list as long as it is greater than 0. In this example, 0 , 1 , and 2 are all multiplied with themselves, but only the results 1 ( 1 * 1 ) and 4 ( 2 * 2 ) satisfy the greater than 0 condition and become part of the ...
Different Forms of Assignment Statements in Python
Python Return Statements Explained: What They Are and Why You Use Them. freeCodeCamp. All functions return a value when called. If a return statement is followed by an expression list, that expression list is evaluated and the value is returned: >>> def greater_than_1(n): ... return n > 1.
Understanding the Return Statement. The return statement in Python is used to exit a function and return a value to the caller. It allows you to pass back a specific result or data from a function, enabling you to utilize the output for further computation or processing. The return statement is often placed at the end of a function and marks ...
7. Simple statements — Python 3.12.4 documentation
Unpack a tuple and list in Python; You can also swap the values of multiple variables in the same way. See the following article for details: Swap values in a list or values of variables in Python; Assign the same value to multiple variables. You can assign the same value to multiple variables by using = consecutively.
The return statement is used inside a function block to send a value or object back to the caller. When return is executed, the function exits immediately, passing back the specified return value. For example: def add(a, b): return a + bsum = add(2, 3)print(sum) # Prints 5. Here, the add () function returns the sum of its two arguments.
Assignment Expressions. For more information on concepts covered in this lesson, you can check out: Here's a feature introduced in version 3.8 of Python, which can simplify the function we're currently working on. It's called an assignment expression, and it allows you to save the return value of a function to a variable while at the same ...
12.5. Returning a value from a function
As an experienced Python developer, a key skill is knowing how to effectively return multiple values from functions. Python provides built-in data structures like tuples, lists, and dictionaries to enable returning multiple values with ease. In this comprehensive guide, you'll unlock expert knowledge on:
1. The += operator is part of a set of multiple Augmented Assignment Operators. You can think of these as a shortcut for Assignment Statements where the variable being assigned is also in the value being assigned to the variable. So, i += 1 is identical to i = i + 1.
I have a function which calculate the max in a list: def max_in_list(list): max = 0 for i in range(len(list)-1): if list[i] > list [i+1] and list [i] > max: max =...
Is there a way to specify in return value annotation that a list of floats is output only when the input ids is a list of strs or ints? python; python-typing; Share. ... You only feel compelled to combine them into a single function (for "convenience") because Python lacks a built-in function that makes gets easy to create on the fly from get.