4 key Python shortcuts that you need to know

Vidya Gopinath for keySkillset Vidya Gopinath for keySkillset
Vidya Gopinath for keySkillset
12
September
2023
4 key Python shortcuts that you need to know

Want to jumpstart your career in Tech? You will find some useful Python shortcuts here. This is the list of 4 key shortcuts that every Python learner needs to know. You cannot miss them. Python, known for its simplicity and versatility, offers a plethora of shortcuts that can significantly boost your productivity and code elegance. These four key shortcuts are absolute must-knows for any Python enthusiast.

Meanwhile, if you wish to know why you should avoid duplicating codes, you need to check out this avoid duplicating code blog

Shortcut #1: F-Strings

F-Strings are a feature introduced in Python version 3.6 and above. They provide a convenient way to embed Python expressions or variables within strings without the need for explicit concatenation or string formatting. Here's how to use F-Strings:

# F-Strings

# Define a variable 'name' with the value "Tim"

name = "Tim"

# You can print the string with 'name' using different methods:

# Method 1: Using a comma to separate the string and 'name'

print("Hello", name)

# Method 2: Using concatenation with the plus operator

print("Hello" + name)

# Method 3: Using an F-String

print(f'Hello {name}')

# F-Strings allow for more flexibility:

# You can add text before and after the expression

# You can embed multiple expressions

# Example: Repeating 'name' twice

print(f'Hello {name} {name}')

# You can perform calculations within an F-String

# Example: Adding 2 and 3

print(f'Hello {name} {2 + 3}')

# You can even include lists

# Example: Including a list [1, 2, 3]

print(f'Hello {name} {[1, 2, 3]}')

# You can assign an F-String to a variable for later use

X = f'Hello {name}'

# And then print the variable to display the same result

print(X)

F-Strings are a powerful tool for creating formatted strings in Python 3.6 and above, making it easier to embed variables and expressions directly within your text.

Shortcut #2: Unpacking 

Unpacking in Python is a highly useful feature that allows you to assign variables to the values within collections, such as lists, dictionaries, and strings. It eliminates the need for repetitive assignments and results in more concise code. Let's explore how unpacking works with various collections:

Unpacking a Tuple:

# Unpacking a tuple

tup = (1, 2, 3, 4, 5)

a, b, c, d, e = tup

print(a, b, c, d, e)  # Output: 1 2 3 4 5

Unpacking a List:

# Unpacking a list

lst = [1, 2, 3, 4, 5]

a, b, c, d, e = lst

Unpacking a String:

# Unpacking a string

string = "hello"

a, b, c, d, e = string  # Each character is assigned to a variable

Unpacking a Dictionary:

# Unpacking a dictionary (keys are assigned by default)

dic = {"a": 1, "b": 2}

a, b = dic  # a will be "a", b will be "b"

If you want to extract values from a dictionary, you can use .values():

a, b = dic.values()  # a will be 1, b will be 2

To unpack dictionary items (key-value pairs), you can use .items():

for key, value in dic.items():

 print(key, value)  # Output: a 1, b 2

Unpacking Coordinate Values:

# Unpacking coordinate values

coords = [4, 5]

x, y = coords

print(x, y)  # Output: 4 5

It's important to note that when unpacking, you must have the same number of variables on the left-hand side as there are values in the collection. If they don't match, you'll encounter an error. For example, attempting to unpack coords into x, y, z would result in an error because there are not enough values to assign to all three variables. Unpacking is a powerful and efficient way to work with collections in Python.

Shortcut #3: Comprehensions 

So, let's now move on to a more popular and very useful Python shortcut. We have comprehension. Here's a simplified and reorganized explanation of list comprehensions in Python:

# List Comprehensions

# Initializing a list with zeros using a for loop

X = []

for i in range(100):

    X.append(0)

# The Pythonic way using list comprehension

X = [0 for _ in range(100)]

# Adding condition to include even numbers

X = [i for i in range(100) if i % 2 == 0]

# Using nested for loops

X = [i for i in range(100) for j in range(10)]

# Creating a two-dimensional list

X = [[0 for _ in range(5)] for _ in range(5)]

# You can use underscores (_) when you don't need the variable/iterator

List comprehensions provide a concise and readable way to create lists in Python, and you can apply similar comprehensions to other data structures like dictionaries and tuples as well.

Shortcut #4: Object Multiplication 

In Python, you can multiply various objects, not just numbers, but also strings, lists, and more. Let's explore some examples:

Multiplying Strings:

text = "hello" * 5

print(text)

Output: 

Hellohellohellohellohello

Multiplying Lists:

numbers = [1, 2, 3] * 5

print(numbers)

Output: 

[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

Multiplying Nested Lists:

nested_list = [[1, 2, 3]] * 5

print(nested_list)

Output:

[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

Multiplying Tuples:

tuple_numbers = (1, 2) * 5

print(tuple_numbers)

Output: 

(1, 2, 1, 2, 1, 2, 1, 2, 1, 2)

You can use multiplication with a variety of objects like strings, lists, and tuples to achieve different outcomes in Python.

Conclusion 

Python's shortcuts are more than just conveniences; they're tools for unleashing your coding creativity. With F-Strings, Unpacking, Comprehensions, and Object Multiplication in your arsenal, you'll not only write more efficient code but also find joy in the elegance and power of Python.

So, gear up, dive in, and let Python's shortcuts propel your programming journey to new heights. The possibilities are limitless, and the adventure is boundless. You can also check out keySkillset for Python Beginner and Intermediate courses to get proficient in Python. Happy coding!

Click here to view the resourceClick here to download the resource
Begin your simulation journey today

Start learning new skills with the help of KeySkillset courses and our learning management system today!