Looping
- Retrieve key, and value of a dictionary in a loop at the same time:
large_language_models = { "llama": "Can do dialogue generation and language translation.", "gpt-4": "Accepts text, and images as input.", } for key, value in large_language_models.items(): print(key.upper() + ": " + value)
- Get the index and value of a sequence at the same time:
predictive_text = ["Hi", "What's up", "Aha"] for index, text in enumerate(predictive_text): print(str(index) + ": " + text)
- Pair elements of two more more sequences with
zip
:questions = [ 'What can I do when getting "We are no longer accepting questions/answers from this account"?', 'How do I ask and answer homework questions?'] answers = ["https://meta.stackoverflow.com/questions/255583", "https://meta.stackoverflow.com/questions/334822"] for question, answer in zip(questions, answers): print(question) print("\t", answer)
- Loop from the end to the start:
oil_prices = [70.10, 73.58, 74.19, 3.946, 1.959] for price in reversed(oil_prices): print(price)
- Loop over a sorted list:
oil_prices = [70.10, 73.58, 74.19, 3.946, 1.959] for price in sorted(oil_prices): print(price)
- Idiomatic way to loop over unique elements of a sorted sequence:
groceries = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] for grocery in sorted(set(groceries)): print(grocery)
- Create a new list instead of modifying the one that you’re looping over it:
years = [7010, 7358, 7419, 3946, 1959] stone_eras = [year for year in years if year < 5000] print(stone_eras)
Conditions
- We can use any operator in
while
andif
. E.g.:- Membership test operators:
in
, ornot in
. - Object identity checkers:
is
, andis not
.
- Membership test operators:
- Chain comparisons:
a < b == c
tests whethera
is less thanb
and moreoverb
equalsc
. - We can negated the result of an expression with
not
. - Boolean operators:
and
,or
.- AKA short-circuit operators.
- Evaluated from left to right.
- Evaluation stops as soon as the outcome is determined.
- E.g. if
A
andC
are true butB
is false,A and B and C
does not evaluate the expressionC
.
- Return value of a short-circuit operator is the last evaluated argument. E.g.:
string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' non_null = string1 or string2 or string3 print(non_null)
- Use Walrus operator to combine comparison and assignment in one expression:
Normal Walrus numbers = [1, 2, 3, 4] for num in numbers: square = num * num if square > 5: print(square)
Or a bit more Pythonic way of coding :wink::numbers = [1, 2, 3, 4] for num in numbers: if (square := num * num) > 5: print(square)
Not related to Walrus operator but just to show how powerful Python really is:numbers = [1, 2, 3, 4] squares = [square for num in numbers if (square := num * num) > 5] print(squares)
numbers = [1, 2, 3, 4] squares = [result for result in [num * num for num in numbers] if result > 5] print(squares)
Comparing Sequence Types
-
Uses lexicographical ordering:
- The first two items are compared, if they differ this determines the outcome of the comparison. End!
- If they are equal, the next two items are compared, and so on, until either sequence is exhausted.
word1 = "EDUCATIVE" word2 = "EDUCATED" print(word1 < word2) print(sorted([word1, word2]))
-
If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively.
tuple1 = (1, 2, ('aa', 'ab')) tuple2 = (1, 2, ('abc', 'a'), 4) print(tuple1 < tuple2) # True
-
You can compare objects of different type IF they have appropriate comparison methods, e.g. 0 is equal to 0.0.
[1.0, 2, 4] == [1, 2, 4]
Practice every day!