Useful objects for loops | COMP70050: Introduction to Machine Learning | Department of Computing | Imperial College London home article Introduction to Machine Learning COMP70050 Autumn Term 2021/2022 Introduction to Python for Java programmers The Zen of Python Example Python program Python vs. Java - Main method Python vs. Java - Variable declaration Python vs. Java - Semicolons Python vs. Java - Braces Python vs. Java - Comments Running Python Running Python as a script Running Python interactively Basic built-in data types Everything is an object Reserved words Variables - Java vs. Python Python Variables Objects in Python Operators Assignment operator Lists Accessing Lists Modifying Lists Tuples Strings are sequences Formatting strings Sets Dictionaries Grouping data with dict and tuple Control flow Loops Useful objects for loops List comprehensions Functions Function arguments Built-in functions Object-Oriented Programming in Python Constructor Attributes Methods Magic/Dunder methods Inheritance Encapsulation Encapsulation the Pythonic way What about protected? Python modules Custom modules What's in a __name__? Handling text files Reading CSV files Writing to CSV files Handling JSON files Pickle That's a wrap! Useful objects for loops Below are three useful built-in objects that are often used with for loops. range() If you would like to simulate a traditional ‘counter’ style Java for loop, you can iterate over a range sequence object/type instead. >>> for i in range(0, 10):
... print(i)
If you run the example above, you will find that range(0, 10) generates a sequence of numbers from 0 (inclusive) to 10 (exclusive). The first parameter (start) is optional, and defaults to 0. range(10) is equivalent to range(0, 10) >>> for i in range(10):
... print(i)
There is also an optional third step parameter. A bit like in Java for loops, it controls how much you increment the counter after each step. >>> for i in range(0, 10, 2):
... print(i)
TIP: If you need a list of numbers, then just convert range to a list! >>> print(range(0, 5))
>>> print(list(range(0,5)))
enumerate() Sometimes you may need both the index and the element in the list in a for loop. [US Billboard Hot 100 Chart Week of October 3, 2020] # Title 1 Dynamite 2 WAP 3 Holy 4 Laugh Now Cry Later enumerate() will provide you with the index (starting at 0 by default) as well as the element in the list. >>> top_hits = ["Dynamite", "WAP", "Holy", "Laugh Now Cry Later"]
>>> for (position, title) in enumerate(top_hits):
... print(f"At number {position} we have {title}!")
...
At number 0 we have Dynamite!
At number 1 we have WAP!
At number 2 we have Holy!
At number 3 we have Laugh Now Cry Later!
Oops! The Billboard Chart does not have a position #0! Let’s fix that. You can either add 1 to the position variable… >>> for (position, title) in enumerate(top_hits):
... print(f"At number {position + 1} we have {title}!")
...
Or give enumerate an optional second argument to tell it to start the index at 1. >>> for (position, title) in enumerate(top_hits, 1):
... print(f"At number {position} we have {title}!")
...
zip() zip() is easier explained with an example. >>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> print(list(zipped))
[(1, 4), (2, 5), (3, 6)]
>>> for (a, b) in zip(x, y):
... print(f"{a}, {b}")
...
1, 4
2, 5
3, 6
<< Previous Next >> Page designed by Josiah Wang Department of Computing | Imperial College London