You Think Sets Are Hard but They Actually Aren’t
Categories: General, Tech | Pubby Cash Received:
Similar to a list, a set is a collection that is unordered and unindexed. In Python, sets are written with curly brackets. The difference from lists is that you cannot access items in a set by referring to an index since sets are unordered the items has no index. However, you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the 'in' keyword. A Python set also resembles a dictionary because it cannot have duplicate values. This makes it easy when you want to store usernames from your website. When a user wants to create a new username, the program will first check if that username is in the set, and if not, then it will add the username to the set. One thing that surprised me was that sets were unordered. You might expect an item to be at that location when you add it but that’s not always the case. Since sets are unordered, so you cannot be sure in which order the items will appear. Unfortunately, you cannot change a value in a set, only add to it. To add one item to a set, use the ‘add()’ method. Use the ‘update()’ method to add more than one item to a set. Sets are easy to work with once you get the hang of it!
Published from: Pennsylvania US
Liked by: Evan Tang, H2O, fnfOzvSR