Python: Tuples and Sets

Tuples

Tuples are a grouping of data in Python similar to a list, except tuples are immutable, meaning you cannot add or delete items from the tuple.

Tuples are created using  () instead of []. A tuple with a single value still requires a comma though. x = (1,)

pythontuple

Notice attempting to delete an element from the tuple results in an error.

Try your code in our online Python console:  

Set

Sets are another method of hold data collections, but they have some interesting factors other methods do not. Sets are very useful as they only return unique elements for the data they store.

pythontuple2.jpg

Looking at the example below, notice how the second set has 4 elements, but the output is only 3. This is due to the fact that sets only return unique values.

You create a set using set() like above, or you can just use {}

pythontuple1.jpg


Try your code in our online Python console:  

If you enjoyed this lesson, click LIKE below, or even better, leave me a COMMENT. 

Last Lesson:  Working with dictionaries

Next Lesson: Conditional Logic

Back to Python Course: Course

One thought on “Python: Tuples and Sets

  1. Pingback: Python for Data Science – Analytics4All

Leave a Reply