python-touples.md

#Python Tuples

Tuples are used to store multiple items in a single variable. It is one of four built-in data types in Python used to store collections of data; the others are List, Set, and Dictionary, each with distinct qualities and use cases.

A tuple is a collection that is ordered and unchangeable.


#Key Characteristics

#Basic Syntax

Tuples are written with round brackets ().

pythonthistuple = ("apple", "banana", "cherry")
print(thistuple)

#Indexed Access

Tuple items are indexed. The first item has index [0], the second has index [1], and so on.


#Tuple Length

To determine how many items a tuple has, use the len() function:

pythonthistuple = ("apple", "banana", "cherry")
print(len(thistuple)) # Output: 3

#Creating a Single Item Tuple

To create a tuple with only one item, you must add a trailing comma. Otherwise, Python will identify the variable as a string (or whatever the item type is).

python# Correct way to create a one-item tuple
thistuple = ("apple",)
print(type(thistuple)) # <class 'tuple'>

# NOT a tuple
thistuple = ("apple")
print(type(thistuple)) # <class 'str'>

#Data Diversity

Tuple items can be of any data type and can even contain a mix of different types.

python# Tuples with uniform data types
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

# Tuple with mixed data types
mixed_tuple = ("abc", 34, True, 40, "male")

#The type() Function

From Python's perspective, tuples are objects with the data type tuple.

pythonmytuple = ("apple", "banana", "cherry")
print(type(mytuple)) # <class 'tuple'>

#The tuple() Constructor

You can also use the tuple() constructor to create a tuple. Note the double round brackets.

pythonthistuple = tuple(("apple", "banana", "cherry"))
print(thistuple)

#Summary of Python Collections

Here is a quick breakdown of the four built-in collection data types in Python:

CollectionOrderedChangeableDuplicatesNotes
ListYesYesYesMost flexible collection.
TupleYesNoYesFaster and safer for data that shouldn't change.
SetNoNo\*NoItems are unindexed. No duplicate members.
DictionaryYes\\YesNoKey-value pairs. No duplicate keys.

\Set items are unchangeable, but you can remove and add new items. \\*As of Python version 3.7, dictionaries are ordered. In 3.6 and earlier, they are unordered.