From c361b4bccab4aa1050a5d80c30984a0890d4a546 Mon Sep 17 00:00:00 2001 From: arpithub Date: Wed, 3 Apr 2024 04:51:21 +0530 Subject: [PATCH] Underscore in python --- _posts/2024-04-02-python-underscode.md | 38 ++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 _posts/2024-04-02-python-underscode.md diff --git a/_posts/2024-04-02-python-underscode.md b/_posts/2024-04-02-python-underscode.md new file mode 100644 index 0000000..4d55850 --- /dev/null +++ b/_posts/2024-04-02-python-underscode.md @@ -0,0 +1,38 @@ +--- +layout: post +title: Uses of Underscore in Python +subtitle: Underscore examples in Python +cover-img: /assets/img/path.jpg +thumbnail-img: /assets/img/thumb.png +share-img: /assets/img/path.jpg +gh-repo: arpithub/arpithub.github.io +gh-badge: [star, fork, follow] +tags: [python,python_tips] +comments: true +--- + +We all have seen underscode symbol in Python. One of the most common uses of the underscore is as a placeholder variable. When iterating over a sequence or generating a range of values, there are often situations where the loop variable is not needed. In such cases, Python programmers opt to use _ as a concise way to indicate that the value is irrelevant to the current context. + +```python +for _ in range(10): + print("Doh!") +``` + +Here, _ acts as a placeholder for the loop variable, highlighting the intent to iterate a specific number of times without the need to reference the loop index. + +Moreover, _ serves as a convention for denoting unused variables. In scenarios where only one value from a function call or tuple unpacking is required, Python programmers often assign the unused value to _, signaling to others that the value is intentionally disregarded. + +```python +first_name, _ = get_name() +``` +This will return multiple parameters but we ignore other parameters except `first_name`. + +```python +>>> 1 + 2 + 3 +6 +>>> _ * 5 +30 +``` +Here underscode saves the value of last expression ie. `1+2+3=5` + +In short, Underscore `_` can be used as a placeholder, unused variable indicator or temporary result storage. It makes our code readable and expressive. Happy Code Writing! \ No newline at end of file