Python Sets

In our last article we left off discussing Python’s version of arrays (the list and dictionary). I also gave you a brief introduction to some Operators. In this tutorial I will tell you about Python’s remaining data holder, Sets, and prepare you for a later discussion of Operators in Python.

Setting It Up

Although I said Lists do not have indexes in the previous article, it isn’t quite true, as I demonstrated. Sets, which are used to hold a bunch of unordered values, truly have no index. And unlike Tuples and Lists, Sets can contain no duplicate data. To assign value to a set, simple do this:


#!/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese'])

gangpassword = Set (“rubble”)


print mcdonaldgang

print gangpassword

The above code creates a set and assigns values to it (Grimace, Hamburglar, and Mayor McCheese). We then create a second set with the gang’s password in it (rubble). Finally, we print out the values of each. Note that there is no index in Sets, so there is no particular order that the values would print:

  Grimace Mayor Mccheese Hamburglar

  Rebubl

{mospagebreak title=Adding to a Set}

Let’s say the Burger King wasn’t having things his way and decided to quit and join the McDonald’s gang. After a rough initiation (he gunned down Jack from Jack in the Box), he is allowed in. Since Ronald is a demanding boss, we want to add him to our Set. We could do so this way:


#!/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese'])

print mcdonaldgang

mcdonaldgang.add(‘Burger King’)

print mcdonaldgang

The above would first print out our original set, then add the Burger King to it, and print it once more:

  Hamburglar, Grimace, Mayor Mccheese

  Hamburglar Burger King Grimace Mayor Mccheese

Let’s say not only the Burger King, but Wendy herself wanted to join the gang. To add more than one new element at the same time, we would use the Update function:


!/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese'])

print mcdonaldgang

mcdonaldgang.update(['Burger King', 'Wendy'])

print mcdonaldgang

Again, we set the initial values for the set mcdonaldgang, printed those values, then used the update function to add two more elements to the set. The resulting print out would be:

  Grimace Mayor Mccheese Hamburglar

  Hamburglar Mayor Mccheese Grimace Wendy Burger King

Again note that Sets do not allow for duplicate values. Let’s say the Fry Guys all wanted to join the McDonald’s Gang. Let’s add them to our database and see what happens.


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy'])

print mcdonaldgang

mcdonaldgang.update(['Fry Guy', 'Fry Guy', 'Fry Guy'])

print mcdonaldgang

This will result in the print out:

  Grimace Mayor Mccheese Hamburglar Burger King Wendy

  Fry Guy Grimace Mayor Mccheese Hamburglar Burger King Wendy

As you can see it only adds the one Fry Guy. Too bad for the rest of them. That’s what you get for all having the same name.

{mospagebreak title=Copying Sets and Testing for Membership}

If you want to copy a Set, you can do so pretty simply:


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])

gang = mcdonaldgang.copy()

print gang

Here would be the result of this program:

  Fry Guy Grimace Mayor Mccheese Hamburglar Burger King Wendy

Suppose the gang had grown so large Ronald couldn’t keep track of it in his head. To see if someone was in his gang, he could use the In operator.


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])


‘Grimace’ in mcdonaldgang

‘Birdie’ in mcdonaldgang

This program checks to see if Grimace and Birdie are in the McDonald’s Gang. Here is the result:

  True

  False

Meaning that Grimace is in the gang, but Birdie is not. Who cares…she was annoying anyway. And now you know where those chicken nuggets come from.

{mospagebreak title=Removing Data from A Set}

As happens in gangs, sometimes members disappear. Let’s say that Colonel Sanders has had enough of the McDonald’s Gang encroaching on his turf. Se he sets loose the hound from hell, aka the Taco Bell dog. The end result is the demise of the Hamburglar.

  Rubble Rubble.

There are three ways Ronald can remove the Hamburglar from the Set. Here they are.

Pop Goes the Greaseball

The first method for deleting an element from a Set is the pop. It simply removes an element from the set.


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])


mcdonaldgang.pop()

The pop method may or may not remove the Hamburglar. This is because the pop method knows no rules. It deletes who it wants, when it wants. It picks an element at random, and deletes them. Period.

If you want to specifically remove the Hamburglar, you might want to try out Pop’s more lawful cousin, the Remove function:


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])


mcdonaldgang.remove(‘Hamburglar’)

print mcdonaldgang

The Remove function will remove the element that you specify. When we print out our list it will be:

  Grimace Wendy Mayor Mccheese Fry Guy Burger King

The only problem with the Remove function is that if you make a typo or the value does not exist in the Set, an error will be returned. To overcome this problem, simply use our third function, the Discard function.


/usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])


mcdonaldgang.discard(‘Hamburglar’)

print mcdonaldgang

This gives us the same result:

  Grimace Wendy Mayor Mccheese Fry Guy Burger King

Lastly, if we wanted to remove all of the data in a Set, we can use the Clear function.


usr/local/bin/python


mcdonaldgang = Set (['Grimace', 'Hamburglar', 'Mayor Mccheese', 'Burger King', 'Wendy', 'Fry Guy'])


mcdonaldgang.clear()

{mospagebreak title=Don’t Make Me Repeat Myself!}

You can also perform loops on Sets. Just keep in mind that Sets have no specific order.


usr/local/bin/python


bigword = Set (“acetylsalicyclic”)


for n in bigword:

print n,

This will print out every letter in the word acetylsalicyclic. Again since there is no order in Sets, it will print the letters out randomly:

  a t y e c l a s i l c c t y i c

{mospagebreak title=Using Operators on Sets}

In addition to the normal mathematical operators you can use with Sets, the following are also useful:

Union

If you wish to merge two Sets, you can do so with the Union operation:


usr/local/bin/python


firstset = Set([1, 2, 3])

secondset = Set([1, 4, 5, 6])

firstset.union(secondset)


print firstset

This will create a union between the two Sets and print the following (remember: it will not store duplicate data):

  1 2 3 4 5 6

Intersection

If you want to find out if two Sets have any data that are the same, you can use the Intersection operation. Behold!


usr/local/bin/python


firstset = Set([1, 2, 3])

secondset = Set([1, 4, 5, 6])


firsttest.intersection(secondset)

This will return any data that is the same in both Sets. The result here would be:

  1

This is because both sets have an element with the value 1 in it.

Symmetric Difference

If you want to print the values in two Sets that are not the same, you can use the Symmetric Difference function.


usr/local/bin/python


firstset = Set([1, 2, 3])

secondset = Set([1, 4, 5, 6])


firstset.symmetric_difference(secondset)

This would result in the values 2, 3, 4, 5, 6. It will not show 1, because one is in both Sets.

Set Difference

If you want to find what values are in firstset that are not in secondset, you can use the Set Difference operation. I know you are dying to see it, so here it is:


usr/local/bin/python


firstset = Set([1, 2, 3])

secondset = Set([1, 4, 5, 6])


firstset.difference(secondset)

This results in the values 2 and 3. This is because the values 2 and 3 are not in the secondset Set, whereas the number 1 is.

So we did not get to discuss Operators in this article; however, we will definitely discuss them in our next episode, as they will be the focus. In the meantime, here is that Operator Table again, just to refresh your memory:


Symbol

Type

What it Does

+

Mathematical

Addition

-

Mathematical

Subtraction

*

Mathematical

Multiplication

/

Mathematical

Division

//

Mathematical

Truncating Division

**

Mathematical

Powers

%

Modulos

Returns the remainder from a division

<<

Shift

Left Shift

>>

Shift

Right Shift

&

Logical

And

|

Logical

Or

^

Logical

Bitwise XOR

~

Logical

Bitwise Negation

<

Comparison

Less than

>

Comparison

Greater than

‘==’

Comparison

Equal to

!=

Comparison

Not Equal To

>=

Comparison

Greater than or Equal To

<=

Comparison

Less than or Equal To

‘=’

Assignment

Assigns a value

+=

Assignment

Adds and assigns a value

-=

Assignment

Subtracts and Assigns a value

*=

Assignment

Multiplies and assigns a value

/=

Assignment

Divides and assigns a value

//=

Assignment

Truncate Divides and assigns a value

**=

Assignment

Powers and assigns

%=

Assignment

Modulus and assigns

>>

Assignment

Shifts and assigns

<<

Assignment

Shifts and assigns

And

Boolean


Or

Boolean


Not

Boolean


Till then…

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort