Python Interview Questions : Lists and Tuples in Python: What’s the Difference?

Python Interview Questions | Lists and Tuples in Python: What’s the Difference?




Python is a programming language that is widely used in Data Engineering and Data Analysis. It offers a variety of data structures to handle different types of data. It is widely used in many fields such as Data Engineering, Data Analytics and AI/ML. The most commonly used data structures in Python are lists and tuples. They both looks similar at first glance, but they have some fundamental differences that makes them suitable for different tasks. In this article, we will explain what lists and tuples are, and highlight the differences and also we will learn when to use list and tuple in our code. We will also have some  examples and use cases to help you understand this better.

Lists in Python:


A list is a collection of items or elements that are ordered and mutable, which means that you can add, remove or modify its elements. Lists are defined using square brackets [] as shown, and each elements are separated by a comma. The elements can be of any datatypes (String, float, double, integer etc.,).

Code Snippet on how to create a list in Python:


fruits = ["apple", "banana", "orange", "grape"]

#List can be accessed by iterating with elements or by using index

#Method - 1: iterate over elements
for element in fruits:
  print(element)
  
#Method - 2: iterate over using index of elements
for i in range(0,len(fruits)):
  print(fruits[i])
Out[]:



The code snippet given above will create a list of fruits with four elements of type String. You can iterate over each item as shown in the command to print the elements one after the other. You can also access the elements in the list using its index. Now, let us learn how to update the list in Python that we created by appending the new element to the end of list and deleting one existing element from the list.

Code Snippet to append new element and delete existing one,

#Append element to list at the end
fruits.append("mango")

#Replace existing element in the list
fruits[0] = "kiwi"

#Remove existing element in the list
fruits.remove("orange")

#iterate over and print to verify
for i in range(0,len(fruits)):
  print(fruits[i])
Out[]:



The code given above,
  • adds the new element named "watermelon" to the end of the given list fruits
  • updates the existing element named "apple" to "kiwi", and 
  • removes the element "orange".

Tuples in Python:


A tuple in Python is also knows as a collection of items or elements that are ordered, but they are immutable, which means that once you create a tuple, you cannot change any of its elements in that session. Tuples are defined using parentheses () as shown, and each element is separated by a comma. 

Code Snippet on how to create a tuple in Python:


#tuple
colors = ("red", "green", "blue")

print(type(colors))

#iterate over elements in tuple
for i in colors:
  print(i)
  
#iterate over using index in tuple
for i in range(0,len(colors)):
  print(colors[i])
Out[]:


The code snippet creates a tuple named colors, which consists of three elements of type String in it. To access these elements defined in a tuple, you can use its index, just as like we did in a list case. However, if you try to modify an element in a tuple or trying to append new element at the end, your code will result in error (TypeError or AttributionError) as shown in the below image.


Lists vs. Tuples: What’s the Difference?


The main difference between lists and tuples in Python is their mutability property. Lists are mutable, which means that you can change the list as per requirement once after creating. Tuples, on the other hand, are immutable, which means that you cannot change their elements once you create them.

This fundamental difference has implications for how you use lists and tuples in your code. Lists are suitable for situations where you need to modify the elements in the collection, while tuples are better suited for situations where the data is fixed and unchanging.

Here are some of the key differences between lists and tuples:

Mutability: 

As mentioned earlier, lists are mutable, while tuples are immutable. This means that lists can be changed, while tuples cannot.

Creation: 

Lists are created using square brackets [], while tuples are created using parentheses ().

Use Cases: 

Lists are best suited for situations where you need to modify the elements in the collection, such as adding or removing items. Tuples are best suited for situations where the data is fixed and unchanging, such as storing constants.

Performance: 

Tuples are generally faster than lists, especially when dealing with large datasets. This is because tuples are immutable, which allows them to be optimized for memory usage and processing speed.


Use Case in Real World: When to Use Lists or Tuples


Now that we’ve explained the differences between lists and tuples, let’s discuss when to use each of these data structures. 

Use Lists when,

  • You need to modify the elements in the collection
  • You need to add or remove items from the collection
  • You want to store a collection of heterogeneous data types
  • You need to maintain the order of the elements


Use Tuples when,

  • You need to store a fixed set of values
  • You want to protect the data from being changed accidentally
  • You want to optimize for performance and memory usage

Lists and tuples are both important data structures in Python, but they serve different purposes. Lists are best suited for situations where you need to modify the elements in the collection, while tuples are better suited for situations where the data is fixed and unchanging. By understanding the differences between lists and tuples, you can choose the appropriate data structure for your needs and write more efficient and effective code.

Happy Learning !!!

Post a Comment

0 Comments