Python Tutorials

Overview

Python tuples are used to store multiple items in a single variable. Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Note

Arrays count starting from zero NOT one. So item 1 is position [0], item 2 is position [1], and item 3 is position [2] … and so on.

Creating a Tuple

Tuples are written with round brackets. Tuple items are ordered as created, and CANNOT be changed at a later point.

  • Tuple items are ordered as created (will not change after created)
  • Tuples are unchangeable once created
  • Tuple items can be of any data type (string, int, boolean, etc.)
  • Each item in a tuple can be of a different data type
  • Duplicate items are allowed
my_tuple = ("Ferrari", "Maserati", "Alfa Romeo", "Maserati")

Getting the Number of Items in a Tuple

To determine how many items are in a tuple, the len() function is used.

my_list = ["Ferrari", "Maserati", "Alfa Romeo"]
print(len(my_list))
3

Creating a Tuple with Only One Item

To create a tuple with only one item, you have to add a comma after the item, otherwise will not be recognized it as a tuple.

my_tuple = ("Maserati",)

Using the tuple() Method to Create a Tuple

my_tuple = tuple(("Ferrari", "Maserati", "Alfa Romeo"))

Tuples are Defined as Objects with the Data Type ‘tuple’

my_tuple = ("Ferrari", "Maserati", "Alfa Romeo")
print(type(my_tuple)) #<class 'tuple'>

Python Notes:

  • The most recent major version of Python is Python 3; however, Python 2 is still in use and quite popular, although not being updated with anything other than security updates
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses
  • Python relies on indentation, using whitespace to define scope, such as the scope of loops, functions, and classes; other programming languages often use curly-brackets for this purpose
  • Python string methods return new values, and DO NOT change the original string

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.