Python Tuple vs List: Similarities and Differences, Explained (2024)

In this guide, you’ll learn the similarities and differences between Python tuples and lists. You’ll also understand when you should use a tuple.

List and tuples are both built-in data structures in Python. They can be used to store a collection of elements.

From support for indexing and slicing to containing heterogeneous data types, tuples and lists may appear to have similar functionality. Therefore, understanding the similarities and differences between the two can help you decide which data structure to use.

Let’s begin.

👩🏽‍💻 You can start a Python REPL and follow along with this tutorial. You can also use Geekflare’s online Python editor to code along.

Python Tuple vs List: What are the Similarities?

Let’s start by learning the similarities between lists and tuples. To facilitate better learning, we present examples of both lists and tuples.

Python Tuple vs List: Similarities and Differences, Explained (1)

#1. Python Iterables

In Python, lists are enclosed in a pair of square brackets, whereas tuples are enclosed in parentheses. You can also create a tuple as a set of values separated by commas—without the parentheses.

They are both iterables; so you can loop through them using a for loop.

The code cell below shows how to iterate through a list.

nums = [2,6,7,10]print(f"Type of nums is {type(nums)}")for num in nums: print(num)# OutputType of nums is <class 'list'>26710

As explained below, you can also iterate through a tuple using a loop

nums = (2,6,7,10)# Note: nums = 2,6,7,10 is a valid tuple as well. If needed, run a quick check!print(f"Type of nums is {type(nums)}")for num in nums: print(num)# OutputType of nums is <class 'tuple'>26710

#2. Support for Creation from Other Sequences

The next similarity between lists and tuples is that they can be created from existing sequences such as strings.

sample_str = "Coding!"

The following code cell shows how list(string) returns a list, whose list items are the characters in the string.

list_from_str = list(sample_str)print(list_from_str)# Output['C', 'o', 'd', 'i', 'n', 'g', '!']

Similarly, a tuple can be created from a string or other sequence using tuple(sequence). The code cell below shows how you can do it.

tuple_from_str = tuple(sample_str)print(tuple_from_str)# Output('C', 'o', 'd', 'i', 'n', 'g', '!')

#3. Support for Indexing and Slicing

Python supports zero indexing in which the first element is at index zero, the second at index one, and so on. Python also supports negative indexing, where the last element is at index -1, the second-to-last element is at index -2, and so on.

list_from_str = ['C', 'o', 'd', 'i', 'n', 'g', '!']print(list_from_str[1])# o

The item at index -2 is the second-to-last item, ‘g’.

tuple_from_str = ('C', 'o', 'd', 'i', 'n', 'g', '!')print(tuple_from_str[-2])# g

You can use slicing when you want to work with a small section of the list or tuple. list[start:end] returns a slice of the list starting at the index start and extending up to end – 1. The default value for a start is 0, and the end is the last element in the iterable.

You can slice tuples using the same syntax. Let’s create slices of the list and tuple that we created earlier.

list_from_str = ['C', 'o', 'd', 'i', 'n', 'g', '!']print(list_from_str[0:5])['C', 'o', 'd', 'i', 'n']

In addition to the start and end values, you can also specify a step value. tuple(start:end:step) returns a slice of the tuple from start up to end - 1, in steps of step.

tuple_from_str = ('C', 'o', 'd', 'i', 'n', 'g', '!')print(tuple_from_str[::2])('C', 'd', 'n', '!')

Here, we set the step value to 2. So the slice contains every second element.

#4. Collections of Multiple Data Types

In the examples we’ve considered, all items on the list and tuples were of the same data type.

However, you can store values of different data types within a single list or a tuple.

The code snippet below student_list contains a student’s name as a string, age as an integer, and marks secured as a float.

student_list = ["John",22,96.5]for item in student_list: print(f"{item} is of type {type(item)}")# OutputJohn is of type <class 'str'>22 is of type <class 'int'>96.5 is of type <class 'float'>

We can come up with a similar example for a tuple.

student_tuple = ("Jane",23,99.5)for item in student_tuple: print(f"{item} is of type {type(item)}")# OutputJane is of type <class 'str'>23 is of type <class 'int'>99.5 is of type <class 'float'>

#5. Support for Membership Testing

Both lists and tuples allow you to perform membership testing for the presence of certain items. If you want to check if a specific item is present in a list or a tuple, you can use the in operator.

The expression item in iterable evaluates to True if the iterable contains the item; else, False.

"Alex" in student_list# False"Jane" in student_tuple# True

So far, you’ve learned the similarities between lists and tuples in Python. Next, let’s learn the key differences between the two data structures.

Python Tuple vs List: What are the Differences?

#1. Mutability of Lists and Immutability of Tuples in Python

The most crucial difference between a list and a tuple in Python is that a tuple is immutable. This means you cannot modify a tuple in place.

▶️ Here’s an example.

tuple1 = ("Java","Python","C++")tuple1[0] = "Rust"# Output----> 2 tuple1[0] = "Rust"TypeError: 'tuple' object does not support item assignment

A list is a mutable data structure, so we can modify the list by changing an item at a specific index, as in the following code cell.

list1 = ["Java","Python","C++"]list1[0] = "Rust"print(list1)# Output['Rust', 'Python', 'C++']

#2. Variable Length Lists vs Fixed Length Tuples

Python list is a variable-length data structure.

You can do the following:

  • Add an item to the end of the list
  • Add items from another list to the end of the current list
  • Remove items at a specific index from the list
list1 = [2,3,4,5]# add an item to the endlist1.append(9)print(list1)# add items from list2 to the end of list1list2 = [0,7]list1.extend(list2)print(list1)# remove an item from list1list1.pop(0)print(list1)

▶️ The output of the above code snippet.

# Output[2, 3, 4, 5, 9][2, 3, 4, 5, 9, 0, 7][3, 4, 5, 9, 0, 7]

Tuples are fixed-length data structures. So you cannot add or remove elements from an existing tuple. But you can redefine the tuple to contain different elements.

tuple1 = (2,4,6,8)tuple1 = (1,8,9)print(tuple1)# Output(1, 8, 9)

#3. Size in Memory

We’ll now build on top of what we learned in the previous section: the list is a variable-length data structure.

When you define the list initially, a specific size is allocated for it in memory. Now, when you modify a list using the append() or extend() methods, additional memory should be allocated to store the added elements. This allocation is almost always done more than the number of items you add.

So there’s a need to keep track of the number of items on the list and the allocated space. In addition, as lists are variable length, there’s a pointer that points to the address of the list items.As a result, lists of length k take up more memory than a tuple with the same k elements.

Here’s a simple illustration.

Python Tuple vs List: Similarities and Differences, Explained (2)

You can use the built-in sys module’s getsizeof() method on a Python object to get the size of an object in memory.

import syslist1 = [4,5,9,14]list_size = sys.getsizeof(list1)print(f"Size of list:{list_size}")tuple1 = (4,5,9,14)tuple_size = sys.getsizeof(tuple1)print(f"Size of tuple:{tuple_size}")

A list takes up more memory than a tuple for the same number and value of elements, as verified in the output below.

# OutputSize of list:104Size of tuple:88
Python Tuple vs List: Similarities and Differences, Explained (3)

When Should You Use a Python Tuple?

From the differences and similarities between Python lists and tuples, you know that if you need a mutable collection, you should use a list.

But when should you use a tupleinstead?

We’ll go over that in this section.

#1. Read-Only Collection

Whenever you want a collection to be immutable, you should define it as a tuple. Suppose color = (243,55,103) a tuple containing the RGB values corresponding to a color shade. Defining color as a tuple ensures that it cannot be modified.

In essence, when you need a collection to be read-only: values should not be modified during the program, you should consider using a tuple. This will prevent unintended modification of the values.

#2. Dictionary Keys

For example, you create a dictionary using the list items key_list as the keys. You can use the dict.fromkeys() method to create a dictionary from a list.

key_list = list("ABCD")dict.fromkeys(key_list){'A': None, 'B': None, 'C': None, 'D': None}

Suppose you modify the list to contain ‘D’ as the first element (index 0)—before creating the dictionary.

Now, what happens to the dictionary key ‘A’?

If you try to create a dictionary from key_list and access the value corresponding to the key ‘A’, you’ll run into a KeyError.

key_list[0] = 'D'dict.fromkeys(key_list)['A']---------------------------------------------------------------------------KeyError Traceback (most recent call last)<ipython-input-31-c90392acc2cf> in <module>()----> 1 dict.fromkeys(key_list)['A']KeyError: 'A'

The keys of a dictionary should be unique. So you cannot have a second ‘D’ as a key.

dict.fromkeys(key_list){'B': None, 'C': None, 'D': None} # A is no longer a key.

If you instead use a tuple, such modification is impossible, and you’re less likely to run into errors. Therefore, you should prefer creating a dictionary using the items of a tuple as keys.

key_tuple = tuple("ABCD")dict.fromkeys(key_tuple){'A': None, 'B': None, 'C': None, 'D': None}key_tuple[0] = 'D'---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-12-2cecbefa7db2> in <module>()----> 1 key_tuple[0] = 'D'TypeError: 'tuple' object does not support item assignment

#3. Function Arguments

The immutability of tuples also makes them suitable to be passed in as function arguments.

Consider the following function find_volume() that returns the volume of a cuboid given the dimensions: length, breadth, and height.

def find_volume(dimensions): l,b,h = dimensions return l*b*h

Suppose these dimensions are available in a list called dimensions. The call to find_volume() with dimensions as the argument returns the volume.

dimensions = [2,8,5]find_volume(dimensions)80

You can always change the dimensions stored in a list.

dimensions = [20,8,5]find_volume(dimensions)800

However, sometimes you’ll need the values to remain constant and resist modification. That’s when you should consider storing the arguments as a tuple and using them in the function call.

#4. Return Values from Functions

In Python, you’ll come across tuples in return values from functions. When you return multiple values from a function, Python implicitly returns them as a tuple.

Consider the following function return_even():

def return_even(num): even = [i for i in range(num) if (i%2==0)] return even,len(even)
  • It takes a number num as the argument
  • It returns the list of even numbers in the interval [0,num) and the length of that list.

Let’s set the value of num 20 and call the function.

num = 20

Calling return_even() returns the two values in a tuple. You can call the type() function with the function call as the verification argument.

type(return_even(num)) # <class 'tuple'>

You can print out the return value to verify that it’s a tuple containing the list of even numbers as the first item and the length of the list as the second item.

print(return_even(num))([0, 2, 4, 6, 8, 10, 12, 14, 16, 18], 10)

As there are two items in the tuple, you can unpack them into two variables, as shown below.

even_nums, count = return_even(num)print(even_nums)print(count)[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]10

Conclusion

I hope this tutorial provided a comprehensive comparison of Python tuple vs list.

Let’s wrap up the tutorial with a quick summary:

  • List and tuples are built-in data structures in Python.
  • Similarities: iterables, support for indexing, slicing, different data types, and operator for membership testing.
  • Key difference: Lists are mutable, and tuples are immutable.
  • Other differences: Fixed length of tuples and variable length of lists, smaller size in memory of tuples.
  • When should you use a tuple? For immutable collections, dictionary keys, and function arguments.

Next, check outPython projectsto practice and learn. Or learn methods to remove duplicate items from Python lists. Happy learning! then, happy coding!👩🏽‍💻

Python Tuple vs List: Similarities and Differences, Explained (2024)

FAQs

How are Python lists and tuples similar? ›

In Python, list and tuple are a class of data structures that can store one or more objects or values. A list is used to store multiple items in one variable and can be created using square brackets. Similarly, tuples also can store multiple items in a single variable and can be declared using parentheses.

Which statement correctly explains a difference between lists and tuples? ›

What statement accurately describes the difference between a list and a tuple? A tuple's contents cannot be changed.

What are the major differences between lists dictionaries and tuple explain with example? ›

List and tuple is an ordered collection of items. Dictionary is unordered collection. List and dictionary objects are mutable i.e. it is possible to add new item or delete and item from it. Tuple is an immutable object.

What are the similarities between lists and arrays Python? ›

Similarities between Lists and Arrays
  • Both are used for storing data.
  • Both are mutable.
  • Both can be indexed and iterated through.
  • Both can be sliced.
May 5, 2018

What are three advantages that tuples have in comparison to lists? ›

The advantages of tuples over the lists are as follows: Tuples are faster than lists. Tuples make the code safe from any accidental modification. If a data is needed in a program which is not supposed to be changed, then it is better to put it in 'tuples' than in 'list'.

What are the similarities between list and string in Python? ›

Both strings and lists have lengths: a string's length is the number of characters in the string; a list's length is the number of items in the list. Each character in a string as well as each item in a list has a position, also called an index.

Why is a tuple faster than a list? ›

Tuple is stored in a single block of memory. Creating a tuple is faster than creating a list. Creating a list is slower because two memory blocks need to be accessed. An element in a tuple cannot be removed or replaced.

Why use a tuple instead of a list? ›

Tuples are more memory efficient than the lists. When it comes to the time efficiency, tuples have a slight advantage over the lists especially when we consider lookup value. If you have data that shouldn't change, you should choose tuple data type over lists.

What are some similarities and differences between variables and lists? ›

Lists store multiple items, but variables only store one. When written in Javascript, both start with the keyword var. In Quorum, lists are declared differently than variables. In Quorum, both variables and lists have types, and can only hold that specific type of information.

What is the primary difference between tuples and lists quizlet? ›

The primary difference between tuples and lists is that tuples are immutable. That means that once a tuple is created, it cannot be changed.

What is the difference between tuple list and string in Python? ›

Lists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list and tuples can contain any type of objects. Lists and tuples are like arrays. Tuples like strings are immutables.

What is the difference between list and tuple in Python w3schools? ›

List is a collection which is ordered and changeable. Allows duplicate members. Tuple is a collection which is ordered and unchangeable.

What are the two major differences in tuple and dictionary in Python? ›

Differences between a tuple and a dictionary

A tuple is a non-hom*ogeneous data structure that can hold a single row as well as several rows and columns. Dictionary is a non-hom*ogeneous data structure that contains key-value pairs. Tuples are represented by brackets (). Dictionaries are represented by curly brackets {}.

What is the difference between list tuple and array in Python? ›

The most commonly used data structures are lists and dictionaries. In this article we also talk about tuples and arrays. Tuples have a slight performance improvement to lists and can be used as indices to dictionaries. Arrays only store values of similar data types and are better at processing many values quickly.

What is the difference and similarities between an array and a list? ›

List is used to collect items that usually consist of elements of multiple data types. An array is also a vital component that collects several items of the same data type. List cannot manage arithmetic operations. Array can manage arithmetic operations.

How do you compare similarity between two lists in Python? ›

How to compare two lists in Python?
  1. Using list. sort() and == operator. The list. ...
  2. Using collections. Counter() This method tests for the equality of the lists by comparing frequency of each element in first list with the second list. ...
  3. Using == operator. This is a modification of the first method.
Mar 10, 2021

What are some of the differences and similarities between an array and a linked list? ›

An array is a collection of elements of a similar data type. Linked List is an ordered collection of elements of the same type in which each element is connected to the next using pointers. Array elements can be accessed randomly using the array index. Random accessing is not possible in linked lists.

What are two differences between list and tuple? ›

list vs tuple in python
S. NoListTuple
1Lists are mutable.Tuples are immutable.
2Iteration in lists is time consuming.Iteration in tuples is faster
3Lists are better for insertion and deletion operationsTuples are appropriate for accessing the elements
4Lists consume more memoryTuples consume lesser memory
3 more rows
Aug 29, 2022

What are two advantages and disadvantages of using tuples? ›

Answer. Advantages of tuple over list in python are that they can be sorted, iterated and they maintain their order automatically. Disadvantages would be that you cannot add or remove elements from a tuple once created.

Do tuples have worse performance than lists? ›

Tuples tend to perform better than lists in almost every category: Tuples can be constant folded. Tuples can be reused instead of copied. Tuples are compact and don't over-allocate.

How are strings and tuples similar and different? ›

A string is a sequence of unicode characters with quotation marks on either side of the sequence. A tuple is an ordered sequence of objects or characters separated by commas with parentheses on either side of the sequence.

What is a tuple in Python with example? ›

A tuple is an immutable object, which means it cannot be changed, and we use it to represent fixed collections of items. Let's take a look at some examples of Python tuples: () — an empty tuple. (1.0, 9.9, 10) — a tuple containing three numeric objects.

What are the data structures similar to lists in Python? ›

Tuples are almost identical to lists, so they contain an ordered collection of elements, except for one property: they are immutable. We would use tuples if we needed a data structure that, once created, cannot be modified anymore. Furthermore, tuples can be used as dictionary keys if all the elements are immutable.

Are tuples mutable or immutable? ›

The basic difference between a list and a tuple is that lists are mutable in nature whereas, tuples are immutable.

Why are tuples immutable? ›

Tuples and lists are the same in every way except two: tuples use parentheses instead of square brackets, and the items in tuples cannot be modified (but the items in lists can be modified). We often call lists mutable (meaning they can be changed) and tuples immutable (meaning they cannot be changed).

Why do we need tuples in Python? ›

Tuples are used to store multiple items in a single variable. Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is ordered and unchangeable.

When would you use a list vs tuple vs a set in Python? ›

A list is a collection of ordered data. A tuple is an ordered collection of data. A set is an unordered collection. A dictionary is an unordered collection of data that stores data in key-value pairs.

Are tuples in Python mutable? ›

Tuples are immutable, meaning that once a tuple has been created, the items in it can't change.

Why can you hash a tuple but not a list? ›

Because a list is mutable, while a tuple is not. When you store the hash of a value in, for example, a dict, if the object changes, the stored hash value won't find out, so it will remain the same.

What are the similarities between lists and strings explain? ›

Answer. The similarity between Lists and Strings in Python is that both are sequences. The differences between them are that firstly, Lists are mutable but Strings are immutable. Secondly, elements of a list can be of different types whereas a String only contains characters that are all of String type.

What are the different similarities and differences? ›

A similarity can be defined as the state of likeness. The two components/ things/ ideas/persons bearing resemblance to each other are called similar. Example: A square and a rectangle are similar with respect to the number of sides( four sides for each). A difference can be defined as the state of being dissimilar.

Is A Python list Mutable? ›

The list is a data type that is mutable. Once a list has been created: Elements can be modified. Individual values can be replaced.

What is the difference between a Python tuple and Python list quizlet? ›

What is the main difference between tuples and lists. Tuples are immutable and lists are mutable.

What is the advantage of using tuples over lists quizlet? ›

What is the advantage of using tuples over lists? Processing a tuple is faster than processing a list.

Which statement correctly explains a difference between lists and tuples quizlet? ›

Which statement correctly explains a difference between lists and tuples? List items can be changed, while tuple items can't be changed.

How does Python compare to tuples? ›

Tuples are compared position by position: the first item of the first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.

Is there a difference between tuples and rows? ›

A table row contained in a table in the tablespace is known as a tuple. Typically, a table has rows and columns, where the rows represent records and the columns represent attributes. A tuple is a single row in a database that contains a single record for such a relation.

What is the meaning of tuples? ›

1) In programming languages, such as Lisp, Python, Linda, and others, a tuple (pronounced TUH-pul) is an ordered set of values. The separator for each value is often a comma (depending on the rules of the particular language).

What is the difference between list and dictionary in Python? ›

Both of these are tools used in the Python language, but there is a crucial difference between List and Dictionary in Python. A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values.

How do you get the last value in a list or a tuple? ›

how do you access the last element of the tuple: A=(0,1,2,3) :
  1. + 2. Use negative indexing A=(1,2,3) Print (A[-1]) Output 3 It will return last element Print(A[-2]) Output 2 It will return second last element of tuple. ...
  2. + 3. A[-1] ...
  3. + 1. ...
  4. A[-1]
Mar 22, 2021

What is the difference between a tuple and a list explain with example? ›

In this Article, you will learn the difference between List and Tuple.
...
Summary:
ListTuple
Operations like insertion and deletion are better performed.Elements can be accessed better.
Consumes more memory.Consumes less memory.
Many built-in methods are available.Does not have many built-in methods.
3 more rows

Which of the following describes a difference between a Python tuple and Python list? ›

1 Answer. The main difference between tuple and list is mutability. Lists are mutable i.e. the list can be modified whereas a tuple is immutable i.e. tuple cannot be changed after creating.

What is the difference between tuple list and set? ›

Tuple is a collection of values separated by comma and enclosed in parenthesis. Unlike lists, tuples are immutable. The immutability can be considered as the identifying feature of tuples. Set is an unordered collection of distinct immutable objects.

Is Python tuple immutable? ›

Besides the different kind of brackets used to delimit them, the main difference between a tuple and a list is that the tuple object is immutable. Once we've declared the contents of a tuple, we can't modify the contents of that tuple.

What is the difference between tuple and vector? ›

A tuple is an object that can hold a number of elements and a vector containing multiple number of such tuple is called a vector of tuple. The elements can be of different data types. The elements of tuples are initialized as arguments in order in which they will be accessed.

What are the similarities between string and tuple? ›

Tuple they are immutable like strings and sequence like lists. They are used to store data just like list, just like string you cannot update or edit the tuple to change it you have to create a new one just like strings.

Are tuples and lists identical? ›

Tuples are identical to lists in all respects, except for the following properties: Tuples are defined by enclosing the elements in parentheses ( () ) instead of square brackets ( [] ). Tuples are immutable.

What are the similarities between string and list? ›

Both strings and lists have lengths: a string's length is the number of characters in the string; a list's length is the number of items in the list. Each character in a string as well as each item in a list has a position, also called an index.

What are the two characteristics of a tuple? ›

Tuples have the given characteristics: They are indexed. Tuples are ordered. These are immutable.

What is the difference between tuple list dictionary in Python? ›

A list is a collection of ordered data. A tuple is an ordered collection of data. A set is an unordered collection. A dictionary is an unordered collection of data that stores data in key-value pairs.

What is the major difference between lists and strings in Python? ›

​Lists can contain a mixture of any python objects but string is a only a ordered sequence of characters. Lists are mutable and their values can be changed while strings are mutable. Lists are designated with [] and the elements are separated by commas while string uses " ".

What are the similarities and differences between list and dictionary? ›

A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values. We can create a list by placing all the available elements into a [ ] and separating them using “,” commas.

What is the similarity between list and dictionary in Python? ›

Similarity: Both List and Dictionary are mutable datatypes. Dissimilarity: List is a sequential data type i.e. they are indexed. Dictionary is a mapping datatype.

Top Articles
Latest Posts
Article information

Author: Stevie Stamm

Last Updated:

Views: 5366

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Stevie Stamm

Birthday: 1996-06-22

Address: Apt. 419 4200 Sipes Estate, East Delmerview, WY 05617

Phone: +342332224300

Job: Future Advertising Analyst

Hobby: Leather crafting, Puzzles, Leather crafting, scrapbook, Urban exploration, Cabaret, Skateboarding

Introduction: My name is Stevie Stamm, I am a colorful, sparkling, splendid, vast, open, hilarious, tender person who loves writing and wants to share my knowledge and understanding with you.