Python Tuples

Tuples are used to store multiple items in one variable. They are one of the four data abstractions, meaning they are used to college data. They are defined using parenthesis and have values inside seperated by commas.

Tuple items are ordered, unchangeable, and allow for duplicate values. Tuples are 0 indexed so the first item has an index of 1, second item has a index of 1, third has an index of 2 and so forth. The last item also has an additional index of -1. You can use the format tuple_name[index] to find the tuple value at that particular index. Tuple items can be of any data type, string, integer, float, boolean, etc.

Tuples are ordered meaning the items have a defined order in which they are organized and that order will not change. New items are always placed at the end of the tuple. Tuple items are not changeable meaning we cannot add, remove, or repplace items after the tuple has been created. Tuples also allow for duplicates so we can have multiple items of the same value. If the tuple only has one value, make sure to have a comma after the value to make sure that the computer classifies the tuple correctly.

To find the length of a tuple, use the len() keyword and pass in the tuple name as the parameter.

You can convert other data abstractions like lists, dictionaries, and sets into tuples by using the tuple() function and passing in the data abstraction as a parameter.

To change a list item, you can use indexing similiar to how you would in a list. Furthermore, to add to a tuple, you can do tuple_name += value to add a value to the end. To add or remove items, you must first convert the tuple to a list since a tuple is unchanagebale. To add an item, use .append()/.extend() and to remove an item, use .remove()/.pop(). You can also delete the tuple overall by doing del tuple_name. Finally, you can use .count(item_name) to count the occurance of a specific item.