DEV Community

kalokli8
kalokli8

Posted on • Updated on

How to write shorter code using python in Leetcode

How to get index in a for loop in Python?

Naive: use a variable

count = 0
for i in range(5):
//  some code using count index
    count += 1
Enter fullscreen mode Exit fullscreen mode

Smart: use enumerate function:

for idx, val in enumerate(ints):
    print(idx, val)
Enter fullscreen mode Exit fullscreen mode

How to get unique key from value in dictionary?

// my_dict.items() look like this:
// [("a", 1), ("b", 2), ("c", 3)]

my_dict ={"a": 1, "b": 2, "c": 3}

def get_key(val):
    for key, value in my_dict.items():
        if val == value:
            return key

    return "no match"
Enter fullscreen mode Exit fullscreen mode

my_dict = {"a": 1, "b": 2, "c": 3}
print(get_key(1))
print(get_key(2))

List Comprehension

Syntax:

newlist = [expression for item in iterable if condition == True]
Enter fullscreen mode Exit fullscreen mode

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
output: ['banana', 'cherry', 'kiwi', 'mango']

Top comments (0)