17.12 Getting Objects From a Set

Getting Objects From a Set

Unlike lists, indexing doesn't work with sets. Use a loop to fetch contents instead. Also, you cannot change the size of a set while iterating through it

For example:

for n in {'this', 'may', 'not', 'be', 'in', 'order'}:
		print(n)

View on GitHub

will result in:

be
may
order
not
this
💡

Or, it could result in some other combination of those words since sets are unordered.

Practice

Odd Set Day

Given a set, remove all the even numbers from it, and for each even number removed, add "Removed [insert the even number you removed]". Example: {1,54, 2, 5} becomes {"Removed 54", 1, 5, "Removed 2"}. It is possible to solve this problem using either discard or remove.

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.