Differentiating between python tuple vs list.

B. Sayo
2 min readApr 11, 2021

This article will try to explain and differentiate between the tuple and list data type we have in python. There are five standard data types namely:

  1. Numbers
  2. String
  3. List
  4. Tuple
  5. Dictionary.

LIST

In python, the list data type can be used to store values in an ordered sequence, just similar to array in other programming language. To create a list, opening and closing square bracket are used ([]) while each of the item in the list are separated with a comma(,). The item in the list if in string form will be typed in quote character(“ “) to mark where the string begins and ends. Take a look at an example

value = [‘cat’, ‘dog’, ‘goat’ , 3]

From the above, a list was created containing three string values and one number and each of this list can accessed using an index. Indexes can be only integer values, not floats if not, an error will be thrown. The In python and other programming languages, the index will always start from (0) and not from the conventional (1).

print(value[0]) will output ‘cat’

print(value[1.0]) will print out an error

A list once created, can have values added, removed, or changed. A list value is a mutable data type. For example:

value[1] =’Sheep’ will change the item in the index(1) which is ‘dog’ to the new assigned ‘sheep’.

print(value) will be now[‘cat’, ‘sheep’, ‘goat’, 3].

Tuples

The tuple data type is like a cousin and identical to the list data type. Like list, tuples are also used to store values of different object. To create a tuple, assign a comma to separate items in a parentheses ( ), instead of the square brackets used in list. For example,

Item = (‘banana’, ‘biro’, 1.0)

basket[1] will output ‘biro’

But the main way that tuples are different from lists is that tuples, like strings, are immutable. Tuples cannot have their values modified, appended, or removed. If you have only one value in your tuple, you can indicate this by placing a comma which is called a trailing comma after the value inside the parentheses. Otherwise, Python will think you’ve just typed a value inside regular parentheses. The comma is what lets Python know this is a tuple value. Unlike some other programming languages, in Python it’s fine to have a trailing comma after the last item in a list or tuple. For example,

type((“bag”,)) will output ‘tuple’ as its class while

type((“bag”)) will output ‘string’ as its class.

Tuples can be used to convey to anyone reading your code that you don’t intend for that sequence of values to change. If you need an ordered sequence of values that never changes, a tuple is advisable to use.

--

--