Data Structures in computer science are specialised formats to store data efficiently and organised. It also enables the easy access and modification of data.
Data Structures are not language-dependent, but today we will discuss two of the implicit data structures supported by Python – List and Tuples.
Remember how you use a well-organised to-do list to keep your life clearer and less complicated. These data structures work on the same principle. They support sequential access, i.e., A user can only visit the values they contain in one particular order.
Let’s get deeper into the primary definition of two constructs and then we will discuss their salient features and analyse how they are different from each other.
A list in Python programming is one of the most practiced and dominant data structures.
Unlike other programming languages like C++ or Java having a static array that stores values of the same type, Python has a more flexible and dynamic array known as a “list,” which automatically scales up or down on adding and deleting elements.
Programmers use this versatile data structure to store heterogeneous data sequentially. Data is separated by commas (,) and stored within the square brackets [ ]. It is a powerful tool embedded with indexing and various other features that provide easy access, modification, and deletion of elements.
Sample_List = [12, -1.56, 5.12, [-8, 23, ”a”, ”b”], ”CodingNinjas”]
A tuple is another most used data structure in Python, and it also supports the specialty of storing multiple elements, i.e., heterogeneous data in a single variable, just like List.
A tuple is created by placing all the elements inside parentheses (), separated by commas. The parentheses are optional. However, it is a good practice to use them.
Sample_Tuple = (-3, -1.56, 27, (-8, 23, ”a”, ”b”), ”CodingNinjas”)
Till now, we just had an overview of the fundamentals of the list and tuple. Let’s drill more into the salient features of each and compare the parameters on which these are similar and dissimilar from each other.
Let’s start with the similarities first.
Similarities in Tuple vs List
Types of elements
- List or Tuple need not always be homogeneous; they can store arbitrary objects in a single variable.
- The objects stored in both can be of any type like int, char, float, string, including the nothing type define None Keyword.
- They can contain duplicate values as well.
- Lists can store tuples, and likewise, tuples can store lists.
- In nested tuples, a tuple can keep more tuples. And in nested lists, a list can have more lists.
- For example:
Ordered or Unordered
- List and Tuples are both ordered data structures, which means if we create any of these data structures, print out the results. The result would be in the same order we originally typed it in.
- Below, Python code shows the ordered features of List and Tuple.
#LIST fruits_list=["apple","banana","mango","grapes"] print("Fruit List is: ",fruits_list) #TUPLE colour_tuple=("red","blue","green","yellow") print("Colour Tuple is: ",colour_tuple) Output: Fruit List is: ['apple', 'banana', 'mango', 'grapes'] Colour Tuple is: ('red', 'blue', 'green', 'yellow')
- You can observe from the above output that both list and tuple have maintained their input order.
Easy Access of elements
- Python supports Indexing and Slicing notations in sequential data structures like list and tuple for easy access of elements.
- Indexing allows access and modifies a single cell, using a square bracket [ ] and the position of the desired element.
- Python uses zero-based indexing. That means the first element has an index of 0; the second has index 1, and so on.
- It also supports negative indexing. So, instead of using indexes from 0 and above, we can use indexes from -1 and below.
- From below, Python Code. Let’s see how it works.
#INDEXING IN LIST fruits_list = ["apple", "banana", "mango", "grapes"] print("fruits_list output: ") print(fruits_list) #shows 0-based indexing print(fruits_list[-2]) #negative indexing print() #INDEXING IN TUPLE colour_tuple = ("red", "blue", "green", "yellow") print("colour_tuple output: ") print(colour_tuple) print(colour_tuple[-1]) Output: fruits_list output: apple mango colour_tuple output: blue yellow
- Indexing works on a single element or cell. In contrast, Slicing operates on many cells at once.
- Slicing extracts a portion of a list or tuple. Suppose L is a list, then L[m:n] returns the part of L:
- It starts from the mth index and goes up to n-1, i.e., excludes the nth index.
- Slicing can also be performed using negative indexing.
- Below Python Code shows Slicing Notation in List and Tuple:
#INDEXING IN LIST fruits_list = ["apple", "banana", "mango", "grapes"] print("fruits_list output: ") print(fruits_list[0 : 2]) #shows 0-based slicing print(fruits_list[-3 : -1]) #slicing using negative index print() #INDEXING IN TUPLE colour_tuple = ("red", "blue", "green", "yellow") print("colour_tuple output: ") print(colour_tuple[1 : ]) #This will slice till the last index print(colour_tuple[-4 : -2]) Output: fruits_list output: ['apple', 'banana'] ['banana', 'mango'] colour_tuple output: ('blue', 'green', 'yellow') ('red', 'blue')
After looking at the similarities in List and Tuple so far, now we will shed light on the parameters that make Tuple vs List different from each other.
Differences in Tuple vs List
We have already discussed this in the primary definition of tuple vs list. The list is created by putting different values of multiple types within the square brackets[ ], whereas Tuple uses parenthesis ( ).
Python Code for Creating List
#Empty List sample_list1= print("EMPTY LIST: ",sample_list1) #List with heterogeneous data items sample_list2 = [1, 2, "abc", "def", 4] print("LIST: ", sample_list2) #List with Nested List sample_list3 = [[1, 2], [3, 4], ["a", "b"]] print("NESTED LIST: ",sample_list3) Output: EMPTY LIST:  LIST: [1, 2, 'abc', 'def', 4] NESTED LIST: [[1, 2], [3, 4], ['a', 'b']]
Python Code for Creating Tuple
#Empty Tuple sample_tuple1 =  print("EMPTY TUPLE: ",sample_tuple1) #Tuple with heterogeneous data items sample_tuple2 = ("abc", "def", 4, 5, 6) print("TUPLE: ", sample_tuple2) #Tuple with Nested Tuples sample_tuple3 = ((1, 2), (3, 4), ("a", "b")) print("NESTED TUPLE: ",sample_tuple3) Output: EMPTY TUPLE:  TUPLE: ('abc', 'def', 4, 5, 6) NESTED TUPLE: ((1, 2), (3, 4), ('a', 'b'))
Mutability is the most significant difference between List and Tuple.
- Lists are mutable, whereas Tuples are immutable.
- Lists are mutable means we can change or modify the elements or portion of the list.
Whereas Tuples are immutable, elements of a tuple cannot be modified once assigned.
- The list supports all the functionalities such as removing, modifying and deleting a single element or the entire list, whereas removing individual elements in the tuple is impossible; however, deleting a tuple entirely is possible using the del keyword.
- Below Python code shows the mutability test of both List and Tuple:
#Let’s try to change list elements sample_list = [1, 2, "abc", "def", 4] print("Original List: ", sample_list) sample_list = "codingninjas" print("Changed List: ", sample_list) print() #Lets try to change tuple elements sample_tuple = ("abc", "def", 4, 5, 6) print("Original Tuple: ", sample_tuple) sample_tuple = "codingninjas" print("Changed Tuple: ", sample_tuple) Output: Original List: [1, 2, 'abc', 'def', 4] Changed List: [1, 2, 'codingninjas', 'def', 4] Original Tuple: ('abc', 'def', 4, 5, 6) Traceback (most recent call last): File "<string>", line 11, in <module> TypeError: 'tuple' object does not support item assignment.
TypeError shows that tuple is immutable and it does not change its allocated memory space once assigned.
- Tuples are created faster than lists.
- Why so? Because Python allocates a single and smaller memory to tuples with low overhead, whereas, for lists, Pythons allocates distinct chunks of memory blocks linked together using pointers.
- Regardless of the implementation, lists are variable-sized, while tuple is a fixed-size immutable structure that does not extend its allocated memory further after the initial declaration.
- Hence, In the end, Memory Consumption by tuples is less as compared to Lists.
- Built-in methods are pre-defined programs in a programming language that a user can directly use without worrying about its implementation.
- List and Tuple share only two built-in methods, index() and count(). Other than that, only the list supports various built-in methods like append(), pop(), remove(), insert(), etc., due to its mutable nature.
Below Python Code shows functions of built-in methods:
#Built-in Methods #Lists sample_list = [1, 3, 4, "abc", "def", [8, 9]] ans = sample_list.index(3) print("Index of element 3 in sample_list:", ans) #Tuple sample_tuple = (2, 4, (1, 2), (6, 7)) ans = sample_tuple.index(4) print("Index of element 4 in sample_tuple:", ans) #Let’s check what if element is not present ans = sample_list.index(5) print("Index of element 5 in sample_list: ", ans) Output: Index of element 3 in sample_list: 1 Index of element 4 in sample_tuple: 1 Traceback (most recent call last): File "<string>", line 11, in <module> ValueError: 5 is not in list
ValueError shows that the required element is not present in the list or tuple.
Reference Table for Tuple vs List
Since we have covered every aspect of the list and tuples and learned how similar and different they are in various contexts, let’s create a table between them for quick reference.
|The list is an ordered collection of heterogeneous elements in a single variable.||The tuple is also an ordered collection of arbitrary elements in a single variable.|
|Square brackets[ ] with commas-separated elements create a list.||Parentheses ( ) and commas separated elements create tuples.|
|Lists are mutable.||Tuples are immutable.|
|List is stored in the form of distinct chunks of memory linked together by pointers. Thus it consumes more memory space.||Tuples are stored in single and smaller memory spaces.|
|List supports various built-in methods like append(),pop(),insert(),remove(),clear() ,index(),count() etc.||Tuples support only two built-in methods, index() and count().|
|List is a variable-sized and more flexible data structure.||Tuple is a fixed size, and due to its immutable nature, it resists changes.|
|Dictionary does not support list as key due to its mutable nature.||Dictionary uses tuples as key due to their hashable and immutable nature.|
Guided Path is one of the verticals under CodeStudio. It is a platform developed by some aspiring enthusiasts and working professionals who have experience in companies like Google, Amazon, Microsoft. At CodeStudio you get interview problems, interview experiences, and practice problems that can help you to land your dream job.
Frequently Asked Questions
Tuple and List are ordered collections of different data items in a single variable, but the key difference is that lists are mutable, whereas tuples are immutable.
Tuples are faster than lists.
Tuples are faster because Python allocates memory to tuples in a single and small space, whereas, for lists, the memory is allocated in different chunks linked by pointers.
Yes, tuples can contain lists, and lists can contain tuples.
No, tuples are immutable, so their content cannot be changed.
List and Tuples both are the most used and versatile data structures of Python.
Here, This article briefly explains the key similarities and dissimilarities between tuple vs list in different contexts. So, We started with the fundamental definitions and learned syntax for creating a list and tuple.
We then discussed similar features like types of elements stored in both, easy access of data, etc., followed by the vital differences in mutability, memory usage, and built-in methods.
In the end, a table is created for a quick reference and recap to revise all the key points discussed in the article.
By Aanchal Tiwari