Difference Between Lists and Tuples in Python

Lists and tuples are data structures built into Python that are used to store items in sorted order. They both have very similar functions, but they are different in many ways nonetheless. So, if you want to know how a Python list and tuple are different from each other, this article is for you. In this article, I’ll explain the difference between lists and tuples in Python.

Difference Between Lists and Tuples

Lists in Python are fundamental data types that are used to store an ordered sequence of elements. By using a list, we can store a sequence of values to perform the same operations on all the values together. Tuples are very similar to lists because they also allow the creation of an ordered sequence of elements.

The difference between lists and tuples comes in terms of functionality. A tuple is an immutable data structure which means that you cannot change the values once stored in a tuple. If you want to change values again and again then you should prefer a list over a tuple. The only advantage of using a tuple over a list is that a tuple is slightly faster than a list. So using a tuple can optimise the time complexity of your code.

Lists are created using square brackets. For example, a = [1, 2, 3, 4, 5]. A tuple is created using round parentheses. For example, a = (1, 2, 3, 4, 5). A list can be edited so that you can add and remove items from a list, but once you create a tuple, you cannot add new items to it or modify it in any way. The only way to change a tuple is to convert it to a list first, and then convert the list back to a tuple after making changes to the list.

Below is how you can convert a tuple into a list for making some changes:

a = (1, 2, 3, 4, 5, 6)
b = list(a)
b.append(7)

Now here is how you can convert a list to a tuple after making the changes:

a = tuple(b)
print(a)
Output:
(1, 2, 3, 4, 5, 6, 7)

Also, Read – Python Projects with Source Code.

Summary

So the difference between lists and tuples in Python is:

  1. The list is mutable and a tuple is immutable
  2. Tuples are faster as compared to a list
  3. Lists have more built-in functions and methods as compared to a tuple.

So I hope you now have understood the difference between lists and tuples in the Python programming language. Feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

Coder with the ♥️ of a Writer || Data Scientist | Solopreneur | Founder

Articles: 997

Leave a Reply