Lists and other data sequence types can also be leveraged as iteration parameters in for loops. Rather than iterating through a range(), you can define a list and iterate through that list.
We’ll assign a list to a variable, and then iterate through the list:
The output above shows that the for loop iterated through the list, and printed each item from the list per line.
Lists and other sequence-based data types like strings and tuples are common to use with loops because they are iterable. You can combine these data types with range() to add items to a list, for example:
Here, we have added a placeholder string of 'shark' for each item of the length of the sharks list.
You can also use a for loop to construct a list from scratch:
Similarly, we can iterate through strings:
Iterating through tuples is done in the same format as iterating through lists or strings above.
When iterating through a dictionary, it’s important to keep the key : value structure in mind to ensure that you are calling the correct element of the dictionary. Here is an example that calls both the key and the value:
When using dictionaries with for loops, the iterating variable corresponds to the keys of the dictionary, and dictionary_variable[iterating_variable] corresponds to the values. In the case above, the iterating variable key was used to stand for key, and sammy_shark[key] was used to stand for the values.
Loops are often used to iterate and manipulate sequential data types.
Write a program that outputs every letter of a string using a FOR loop.
Write a program that outputs every item in a list using a FOR loop.
Create a program that asks the user for 5 items, stores them in a list then outputs them individually using a FOR loop.
Thanks [name] from [whichclass][location], Mr McG will get your message…"
[message]"…and will get back to you ASAP via [email]. Catch you soon.
Have a great day!!
K McGuinness - 2018
No personal data will be shared with any third party. The only data processed via this website is anonymous browsing data to best manage your user experience.