This page looks best with JavaScript enabled

Competitive Pythonic Shorthand

 ·  ☕ 5 min read

Competitive programming can be a thrilling challenge, and every second counts. Python, known for its simplicity and readability, also offers a variety of shorthand techniques that can save precious time. In this guide, we’ll explore some of these Pythonic strategies and how they can give you an edge in coding competitions.

List Comprehensions

List comprehensions are a compact way of creating lists. They can replace multi-line for loops with a single line of code.

Here’s an example of creating a list of squares using a for loop:

1
2
3
4
squares = []
for x in range(10):
    squares.append(x**2)
print(squares)  # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

And here it is as a list comprehension:

1
2
squares = [x**2 for x in range(10)]
print(squares)  # Outputs: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Ternary Operator

Conditional expressions, or ternary operators, let you perform an if-else statement in a single line.

Here’s a classic if-else structure:

1
2
3
4
5
6
condition = True
if condition:
    var = "Yes"
else:
    var = "No"
print(var)  # Outputs: "Yes"

And here’s the equivalent ternary operation:

1
2
3
condition = True
var = "Yes" if condition else "No"
print(var)  # Outputs: "Yes"

Lambda Functions

Lambda functions are anonymous functions that are defined on the fly, usually for simple, single-use cases.

Here’s a regular function to add two numbers:

1
2
3
4
def add(x, y):
    return x + y

print(add(5, 3))  # Outputs: 8

And here’s a lambda function doing the same:

1
2
add = lambda x, y: x + y
print(add(5, 3))  # Outputs: 8

Multiple Variable Assignment

Python allows assigning multiple variables at once, which can be very useful for swapping values or initializing several variables.

Here’s a traditional way of swapping two variables a and b:

1
2
3
4
5
6
7
a = 5
b = 10
print(a, b)  # Outputs: 5 10
temp = a
a = b
b = temp
print(a, b)  # Outputs: 10 5

Python allows you to do this in one line:

1
2
3
4
5
a = 5
b = 10
print(a, b)  # Outputs: 5 10
a, b = b, a
print(a, b)  # Outputs: 10 5

Chaining Comparison Operators

Python allows chaining comparison operators, which can make your code more readable and efficient.

Consider the following code:

1
2
3
4
5
x = 5
y = 3
z = 1
if x > y and y > z:
    print("Conditions met")  # Outputs: "Conditions met"

This can be simplified as:

1
2
3
4
5
x = 5
y = 3
z = 1
if x > y > z:
    print("Conditions met")  # Outputs: "Conditions met"

enumerate()

When you need to iterate over a list and also keep track of the index, you can use the enumerate() function instead of manually incrementing a counter.

Here’s an example without enumerate():

1
2
3
4
5
6
my_list = ['apple', 'banana', 'cherry']
index = 0
for item in my_list:
    print(index, item)
    index += 1
# Outputs: 0 apple, 1 banana, 2 cherry

And here’s how you can use enumerate():

1
2
3
4
my_list = ['apple', 'banana', 'cherry']
for index, item in enumerate(my_list):
    print(index, item)
# Outputs: 0 apple, 1 banana, 2 cherry

zip()

When you need to iterate over multiple lists simultaneously, use the zip() function.

Without zip(), you might do something like this:

1
2
3
4
5
list1 = ['apple', 'banana', 'cherry']
list2 = ['red', 'yellow', 'dark red']
for i in range(len(list1)):
    print(list1[i], list2[i])
# Outputs: apple red, banana yellow, cherry dark red

With zip(), the code becomes:

1
2
3
4
5
list1 = ['apple', 'banana', 'cherry']
list2 = ['red', 'yellow', 'dark red']
for item1, item2 in zip(list1, list2):
    print(item1, item2)
# Outputs: apple red, banana yellow, cherry dark red

map() and filter()

Perhaps less useful for competitive programming out of the pack, because they hardly make it more readable or save typing time. The map() and filter() functions are powerful tools for processing lists. map() applies a function to each item in an iterable, while filter() removes items that don’t satisfy a condition.

Here’s an example using a for loop and if statement to square even numbers:

1
2
3
4
5
6
my_list = [1, 2, 3, 4, 5]
squared_evens = []
for x in my_list:
    if x % 2 == 0:
        squared_evens.append(x**2)
print(squared_evens)  # Outputs: [4, 16]

And here’s how you can use map() and filter():

1
2
3
my_list = [1, 2, 3, 4, 5]
squared_evens = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, my_list)))
print(squared_evens)  # Outputs: [4, 16]

I don’t know about you, but I think the above is parenthesis overflow. But it’s there if you need it.

Conclusion

Python’s shorthand techniques are powerful tools for writing efficient and concise code. They can save you time during coding competitions and make your code more readable. However, it’s crucial to understand when and how to use them correctly. Remember, the most important part of programming is writing clear and correct code.


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)