Programs

What is the Difference Between List and Tuple?

Tuple and lists are a type of data structure used in Python. Lists store data in a single variable using square brackets, whereas Tuples store data in one variable with the help of parentheses. Both structures are used for storing multiple values and objects. 

This article will dive into the key differences between list and tuple and explore their use cases. But first, let’s take a quick look at the core similarities between them:

  • You can store items and objects of all data types in both tuples and lists.  
  • Both tuple and list allow data to be accessed using their respective index.  
  • Both these data types can compile and catalog a variety of data items.  

Python Tuple vs List 

1. Syntax Differences

The declaration of lists and tuples is invariably different in Python. Lists are declared using ‘[]’ square brackets, whereas the declaration of tuples is made using ‘()’. 

Here’s an example to better understand how to declare lists and tuples in Python. 

list_num = [7,8,9,10]

tup_num = (10,11,13,14)

print(list_num)

print(tup_num)

The output to this sequence would be. 

[7,8,9,10]

(10,11,13,14)

In this example, a variable named list_num is defined that accommodates numbers from 7 to 10. We also see that the output is enclosed in square brackets. However, the variable defined as tup_num and holds the numbers from 10 to 14 displays an output using parenthesis. 

Python uses a type() function that helps us understand the type of items created. 

print(type(tup_num))

print(type(list_num))

Output:

<class ‘tuple’>

<class ‘list’>

2. Mutability (Mutable vs Immutable) 

Tuples and lists are contradictory when it comes to their mutability. Tuples are immutable structures that can’t be modified or changed after they have been created. On the contrary, lists are mutable structures that can be easily altered or modified after their creation.

Only tuples can be used as a key to the dictionaries because of their immutable nature. Lists can never be used as keys when required. 

3. Changing an object (List vs Tuple)

Let us find out what happens when an attempt to make a change in the list is created. 

name = [alex, rick, martin]

name [0] = “roxy”

Note: the first element is always referred to as 0 and not 1. 

Now let us have a look at what the output would look like after the following command:

>>>name

Output: 

 [roxy, rick, martin]

The output shows how the very first item in the list changed. 

Now let’s see what would be the outcome if a tuple was used. 

name = (alex, rick, martin)

When an item in the tuple is changed using 

name(0) = “roxy” 

The output will be: 

TypeError: ‘tuple’ object does not support item assignment.

This means the tuple data structure does not support an object that was changed later. Therefore, we can conclude that only lists can be modified and not tuples. 

4. Copies vs Reused

One cannot copy tuples. The reason here is the immutable nature of tuples. For instance, if you run a tuple (tup_name), you will see it has been restored to itself. 

Example:

names = (‘allen”,”siri”, “Michaela”)

copyNames = tuple(names)

print(names is copyNames)

The output here will be – “True”.

On the contrary, if you try and do the same for a list, (as illustrated in the example):

Example:

names = [“allen”, “ siri “‘ “Michaela”]

copyNames = list (names)

print(names is copyNames)

The output will be shown as “false”. 

You would have to copy and paste the complete names into the new list for a true output. 

5. Python Tuple vs List | Size Differences 

Because of the tuple’s immutable nature, Python only allocates tuple memories in the form of large blocks with relatively low overhead. For lists, Python only provides memory blocks of smaller sizes. As a result, tuple’s have only a tiny amount of memory compared to lists. However, this means that tuples are much faster to use than lists when many items are involved. 

6. Heterogeneous vs Homogeneous

Tuples can store elements of various types that are heterogeneous. On the contrary, lists can store features or data of the same variant that are homogeneous. 

This, however, is only a semantic difference. For example, lists can store data of various types, and tuples can also store data of the same kind. 

Example: 

list_elements = [‘allen’, 20, ‘mary’]

tuple_elements = (‘allen’, “mary”, ‘alex’)

The code will run seamlessly, even though the list has a combination of numbers and strings. 

7. Length Differences

Lists and tuples also vary in length and size. While tuples vary in length, the length of the tuple is fixed. Therefore, the size of the lists can be changed anytime, unlike the length of the tuples that remain fixed once defined.

Example:

list_names = [‘allen’, ‘mary’, ‘alex’]

list_names.append(“roxy”)

print(list_names)

Output:

[‘allen’,’ mary’,’ alex’,’ roxy’]

The exact output could have also been achieved using the insert() function instead of the append() function when lists are concerned.

However, the tuple data structure does not provide us with any ways to change its size.

8. Uses Cases

Under different circumstances, at least one of these data structures functions well. It usually depends on the coder of the program on which data structure is used. The data structure is chosen based on whether the data items will be rewritten in the future.

Tuples are far more vital as data structures when compared to lists because:

  • Using tuples instead of lists can inform the coder or the data interpreter not to change the information.
  • You can also restore data without keys using a tuple.
  • Tuples are equivalent to dictionaries in Python. 
  • Tuples stored inside a list are very easy to read. 

The immutable and the hashable nature of tuples make them a perfect replacement for dictionaries. On the other hand, you cannot use lists to replace dictionaries because they do not support the _hash_() function. 

Example: 

key_val= {(‘alex’, ‘brave’):124} #Valid

key_val = {[‘alex’, ‘brave’]:124} #Invalid

9. Nesting Lists and Tuples

Tuples and lists can be stored in each other. Tuples that are nested can hold more tuples. Similarly, nested lists can also have more lists. 

10. Debugging

Tuples are much easier to debug in more extensive projects when compared to lists. This is because of the immutable characteristics of tuples. However, when a much smaller amount of data is involved, it is always suggested to rely on lists. Tuples are also much easier to track because they cannot be changed, unlike lists, where bugs are challenging to follow. 

11. Functions and operations

Python has some beneficial functions that can be applied to tuples and lists, such as sorted, sum, all, min, max, lean, etc.

When operations are concerned, one may find many similarities in lists and tuples. However, lists have some extra functionalities that are absent in tuples. These are mostly pop and insert operations, alongside removing and storing items. 

Key Takeaways

  • Tuples have fewer functionalities than lists.
  • The structure of the tuple is immutable, whereas the structure of lists is mutable.
  • Tuples come in fixed lengths, whereas the length of the lists can vary.
  • The syntax of the list is represented by “[]” square brackets, whereas the syntax of tuples is presented in the form of “()” parenthesis. 
  • Tuples consume less memory when compared to lists. 
  • The tuple data structure is best when accessing elements are involved. 
  • The function list is better at performing specific operations of deletion and insertion. 
  • The iterations implicated on tuples are faster than the ones implicated on lists. 
  • The list may have multiple built methods, whereas the tuple has none. 

Learn in detail about Python’s nitty-gritty and its advanced concepts through upGrad’s 18-month Master of Science in Data Science program in collaboration with Liverpool John Moores University and IIIT Bangalore. With industry-leading teaching faculty at your disposal, 500+ hours of learning material, and doubt resolution classes, students stand a chance to master Python and other data science fundamentals to steer their careers accordingly. In addition, the program helps develop competence in over 14 languages & tools like Tableau, MySQL, Excel, MongoDB, and more. 

So, don’t hesitate. Reach out to us today!

When to use Tuples or Lists?

If you need your data items to be read-only, then you should use tuples. Data remains constant in tuples because of their guaranteed availability of never-changing data.

Lists, however, are very mutable. Hence, the data in them can always be changed. Moving, switching, deleting, and adding items to a list is very flexible. They are best used when data requires modification in the later stages of the program cycle.

Are tuples faster when compared to lists?

Yes, creating a tuple takes much less time than creating a list. When lists are made, more than one memory block needs to be accessed. It is because elements in tuples cannot be removed and replaced, whereas the features in lists can be changed several times during the program cycle.

Where are tuples and lists used in real life?

One can make a list to store the required steps to cook a specific dish using a particular recipe. The list involves sequential access to data. Hence, one can access the steps in order. On the other hand, Tuples can be used to store data like the longitude or the latitude of your residence. This is because a tuple is a collection of predefined data. You can also use the same tuple to store the location coordinates of other places.

Learn data science courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Best Data Science Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×