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
Smart: use enumerate function:
for idx, val in enumerate(ints):
print(idx, val)
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"
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]
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)