- Blog Categories
- Software Development Projects and Ideas
- 12 Computer Science Project Ideas
- 28 Beginner Software Projects
- Top 10 Engineering Project Ideas
- Top 10 Easy Final Year Projects
- Top 10 Mini Projects for Engineers
- 25 Best Django Project Ideas
- Top 20 MERN Stack Project Ideas
- Top 12 Real Time Projects
- Top 6 Major CSE Projects
- 12 Robotics Projects for All Levels
- Java Programming Concepts
- Abstract Class in Java and Methods
- Constructor Overloading in Java
- StringBuffer vs StringBuilder
- Java Identifiers: Syntax & Examples
- Types of Variables in Java Explained
- Composition in Java: Examples
- Append in Java: Implementation
- Loose Coupling vs Tight Coupling
- Integrity Constraints in DBMS
- Different Types of Operators Explained
- Career and Interview Preparation in IT
- Top 14 IT Courses for Jobs
- Top 20 Highest Paying Languages
- 23 Top CS Interview Q&A
- Best IT Jobs without Coding
- Software Engineer Salary in India
- 44 Agile Methodology Interview Q&A
- 10 Software Engineering Challenges
- Top 15 Tech's Daily Life Impact
- 10 Best Backends for React
- Cloud Computing Reference Models
- Web Development and Security
- Find Installed NPM Version
- Install Specific NPM Package Version
- Make API Calls in Angular
- Install Bootstrap in Angular
- Use Axios in React: Guide
- StrictMode in React: Usage
- 75 Cyber Security Research Topics
- Top 7 Languages for Ethical Hacking
- Top 20 Docker Commands
- Advantages of OOP
- Data Science Projects and Applications
- 42 Python Project Ideas for Beginners
- 13 Data Science Project Ideas
- 13 Data Structure Project Ideas
- 12 Real-World Python Applications
- Python Banking Project
- Data Science Course Eligibility
- Association Rule Mining Overview
- Cluster Analysis in Data Mining
- Classification in Data Mining
- KDD Process in Data Mining
- Data Structures and Algorithms
- Binary Tree Types Explained
- Binary Search Algorithm
- Sorting in Data Structure
- Binary Tree in Data Structure
- Binary Tree vs Binary Search Tree
- Recursion in Data Structure
- Data Structure Search Methods: Explained
- Binary Tree Interview Q&A
- Linear vs Binary Search
- Priority Queue Overview
- Python Programming and Tools
- Top 30 Python Pattern Programs
- List vs Tuple
- Python Free Online Course
- Method Overriding in Python
- Top 21 Python Developer Skills
- Reverse a Number in Python
- Switch Case Functions in Python
- Info Retrieval System Overview
- Reverse a Number in Python
- Real-World Python Applications
- Data Science Careers and Comparisons
- Data Analyst Salary in India
- Data Scientist Salary in India
- Free Excel Certification Course
- Actuary Salary in India
- Data Analyst Interview Guide
- Pandas Interview Guide
- Tableau Filters Explained
- Data Mining Techniques Overview
- Data Analytics Lifecycle Phases
- Data Science Vs Analytics Comparison
- Artificial Intelligence and Machine Learning Projects
- Exciting IoT Project Ideas
- 16 Exciting AI Project Ideas
- 45+ Interesting ML Project Ideas
- Exciting Deep Learning Projects
- 12 Intriguing Linear Regression Projects
- 13 Neural Network Projects
- 5 Exciting Image Processing Projects
- Top 8 Thrilling AWS Projects
- 12 Engaging AI Projects in Python
- NLP Projects for Beginners
- Concepts and Algorithms in AIML
- Basic CNN Architecture Explained
- 6 Types of Regression Models
- Data Preprocessing Steps
- Bagging vs Boosting in ML
- Multinomial Naive Bayes Overview
- Gini Index for Decision Trees
- Bayesian Network Example
- Bayes Theorem Guide
- Top 10 Dimensionality Reduction Techniques
- Neural Network Step-by-Step Guide
- Technical Guides and Comparisons
- Make a Chatbot in Python
- Compute Square Roots in Python
- Permutation vs Combination
- Image Segmentation Techniques
- Generative AI vs Traditional AI
- AI vs Human Intelligence
- Random Forest vs Decision Tree
- Neural Network Overview
- Perceptron Learning Algorithm
- Selection Sort Algorithm
- Career and Practical Applications in AIML
- AI Salary in India Overview
- Biological Neural Network Basics
- Top 10 AI Challenges
- Production System in AI
- Top 8 Raspberry Pi Alternatives
- Top 8 Open Source Projects
- 14 Raspberry Pi Project Ideas
- 15 MATLAB Project Ideas
- Top 10 Python NLP Libraries
- Naive Bayes Explained
- Digital Marketing Projects and Strategies
- 10 Best Digital Marketing Projects
- 17 Fun Social Media Projects
- Top 6 SEO Project Ideas
- Digital Marketing Case Studies
- Coca-Cola Marketing Strategy
- Nestle Marketing Strategy Analysis
- Zomato Marketing Strategy
- Monetize Instagram Guide
- Become a Successful Instagram Influencer
- 8 Best Lead Generation Techniques
- Digital Marketing Careers and Salaries
- Digital Marketing Salary in India
- Top 10 Highest Paying Marketing Jobs
- Highest Paying Digital Marketing Jobs
- SEO Salary in India
- Brand Manager Salary in India
- Content Writer Salary Guide
- Digital Marketing Executive Roles
- Career in Digital Marketing Guide
- Future of Digital Marketing
- MBA in Digital Marketing Overview
- Digital Marketing Techniques and Channels
- 9 Types of Digital Marketing Channels
- Top 10 Benefits of Marketing Branding
- 100 Best YouTube Channel Ideas
- YouTube Earnings in India
- 7 Reasons to Study Digital Marketing
- Top 10 Digital Marketing Objectives
- 10 Best Digital Marketing Blogs
- Top 5 Industries Using Digital Marketing
- Growth of Digital Marketing in India
- Top Career Options in Marketing
- Interview Preparation and Skills
- 73 Google Analytics Interview Q&A
- 56 Social Media Marketing Q&A
- 78 Google AdWords Interview Q&A
- Top 133 SEO Interview Q&A
- 27+ Digital Marketing Q&A
- Digital Marketing Free Course
- Top 9 Skills for PPC Analysts
- Movies with Successful Social Media Campaigns
- Marketing Communication Steps
- Top 10 Reasons to Be an Affiliate Marketer
- Career Options and Paths
- Top 25 Highest Paying Jobs India
- Top 25 Highest Paying Jobs World
- Top 10 Highest Paid Commerce Job
- Career Options After 12th Arts
- Top 7 Commerce Courses Without Maths
- Top 7 Career Options After PCB
- Best Career Options for Commerce
- Career Options After 12th CS
- Top 10 Career Options After 10th
- 8 Best Career Options After BA
- Projects and Academic Pursuits
- 17 Exciting Final Year Projects
- Top 12 Commerce Project Topics
- Top 13 BCA Project Ideas
- Career Options After 12th Science
- Top 15 CS Jobs in India
- 12 Best Career Options After M.Com
- 9 Best Career Options After B.Sc
- 7 Best Career Options After BCA
- 22 Best Career Options After MCA
- 16 Top Career Options After CE
- Courses and Certifications
- 10 Best Job-Oriented Courses
- Best Online Computer Courses
- Top 15 Trending Online Courses
- Top 19 High Salary Certificate Courses
- 21 Best Programming Courses for Jobs
- What is SGPA? Convert to CGPA
- GPA to Percentage Calculator
- Highest Salary Engineering Stream
- 15 Top Career Options After Engineering
- 6 Top Career Options After BBA
- Job Market and Interview Preparation
- Why Should You Be Hired: 5 Answers
- Top 10 Future Career Options
- Top 15 Highest Paid IT Jobs India
- 5 Common Guesstimate Interview Q&A
- Average CEO Salary: Top Paid CEOs
- Career Options in Political Science
- Top 15 Highest Paying Non-IT Jobs
- Cover Letter Examples for Jobs
- Top 5 Highest Paying Freelance Jobs
- Top 10 Highest Paying Companies India
- Career Options and Paths After MBA
- 20 Best Careers After B.Com
- Career Options After MBA Marketing
- Top 14 Careers After MBA In HR
- Top 10 Highest Paying HR Jobs India
- How to Become an Investment Banker
- Career Options After MBA - High Paying
- Scope of MBA in Operations Management
- Best MBA for Working Professionals India
- MBA After BA - Is It Right For You?
- Best Online MBA Courses India
- MBA Project Ideas and Topics
- 11 Exciting MBA HR Project Ideas
- Top 15 MBA Project Ideas
- 18 Exciting MBA Marketing Projects
- MBA Project Ideas: Consumer Behavior
- What is Brand Management?
- What is Holistic Marketing?
- What is Green Marketing?
- Intro to Organizational Behavior Model
- Tech Skills Every MBA Should Learn
- Most Demanding Short Term Courses MBA
- MBA Salary, Resume, and Skills
- MBA Salary in India
- HR Salary in India
- Investment Banker Salary India
- MBA Resume Samples
- Sample SOP for MBA
- Sample SOP for Internship
- 7 Ways MBA Helps Your Career
- Must-have Skills in Sales Career
- 8 Skills MBA Helps You Improve
- Top 20+ SAP FICO Interview Q&A
- MBA Specializations and Comparative Guides
- Why MBA After B.Tech? 5 Reasons
- How to Answer 'Why MBA After Engineering?'
- Why MBA in Finance
- MBA After BSc: 10 Reasons
- Which MBA Specialization to choose?
- Top 10 MBA Specializations
- MBA vs Masters: Which to Choose?
- Benefits of MBA After CA
- 5 Steps to Management Consultant
- 37 Must-Read HR Interview Q&A
- Fundamentals and Theories of Management
- What is Management? Objectives & Functions
- Nature and Scope of Management
- Decision Making in Management
- Management Process: Definition & Functions
- Importance of Management
- What are Motivation Theories?
- Tools of Financial Statement Analysis
- Negotiation Skills: Definition & Benefits
- Career Development in HRM
- Top 20 Must-Have HRM Policies
- Project and Supply Chain Management
- Top 20 Project Management Case Studies
- 10 Innovative Supply Chain Projects
- Latest Management Project Topics
- 10 Project Management Project Ideas
- 6 Types of Supply Chain Models
- Top 10 Advantages of SCM
- Top 10 Supply Chain Books
- What is Project Description?
- Top 10 Project Management Companies
- Best Project Management Courses Online
- Salaries and Career Paths in Management
- Project Manager Salary in India
- Average Product Manager Salary India
- Supply Chain Management Salary India
- Salary After BBA in India
- PGDM Salary in India
- Top 7 Career Options in Management
- CSPO Certification Cost
- Why Choose Product Management?
- Product Management in Pharma
- Product Design in Operations Management
- Industry-Specific Management and Case Studies
- Amazon Business Case Study
- Service Delivery Manager Job
- Product Management Examples
- Product Management in Automobiles
- Product Management in Banking
- Sample SOP for Business Management
- Video Game Design Components
- Top 5 Business Courses India
- Free Management Online Course
- SCM Interview Q&A
- Fundamentals and Types of Law
- Acceptance in Contract Law
- Offer in Contract Law
- 9 Types of Evidence
- Types of Law in India
- Introduction to Contract Law
- Negotiable Instrument Act
- Corporate Tax Basics
- Intellectual Property Law
- Workmen Compensation Explained
- Lawyer vs Advocate Difference
- Law Education and Courses
- LLM Subjects & Syllabus
- Corporate Law Subjects
- LLM Course Duration
- Top 10 Online LLM Courses
- Online LLM Degree
- Step-by-Step Guide to Studying Law
- Top 5 Law Books to Read
- Why Legal Studies?
- Pursuing a Career in Law
- How to Become Lawyer in India
- Career Options and Salaries in Law
- Career Options in Law India
- Corporate Lawyer Salary India
- How To Become a Corporate Lawyer
- Career in Law: Starting, Salary
- Career Opportunities: Corporate Law
- Business Lawyer: Role & Salary Info
- Average Lawyer Salary India
- Top Career Options for Lawyers
- Types of Lawyers in India
- Steps to Become SC Lawyer in India
- Tutorials
- C Tutorials
- Recursion in C: Fibonacci Series
- Checking String Palindromes in C
- Prime Number Program in C
- Implementing Square Root in C
- Matrix Multiplication in C
- Understanding Double Data Type
- Factorial of a Number in C
- Structure of a C Program
- Building a Calculator Program in C
- Compiling C Programs on Linux
- Java Tutorials
- Handling String Input in Java
- Determining Even and Odd Numbers
- Prime Number Checker
- Sorting a String
- User-Defined Exceptions
- Understanding the Thread Life Cycle
- Swapping Two Numbers
- Using Final Classes
- Area of a Triangle
- Skills
- Software Engineering
- JavaScript
- Data Structure
- React.js
- Core Java
- Node.js
- Blockchain
- SQL
- Full stack development
- Devops
- NFT
- BigData
- Cyber Security
- Cloud Computing
- Database Design with MySQL
- Cryptocurrency
- Python
- Digital Marketings
- Advertising
- Influencer Marketing
- Search Engine Optimization
- Performance Marketing
- Search Engine Marketing
- Email Marketing
- Content Marketing
- Social Media Marketing
- Display Advertising
- Marketing Analytics
- Web Analytics
- Affiliate Marketing
- MBA
- MBA in Finance
- MBA in HR
- MBA in Marketing
- MBA in Business Analytics
- MBA in Operations Management
- MBA in International Business
- MBA in Information Technology
- MBA in Healthcare Management
- MBA In General Management
- MBA in Agriculture
- MBA in Supply Chain Management
- MBA in Entrepreneurship
- MBA in Project Management
- Management Program
- Consumer Behaviour
- Supply Chain Management
- Financial Analytics
- Introduction to Fintech
- Introduction to HR Analytics
- Fundamentals of Communication
- Art of Effective Communication
- Introduction to Research Methodology
- Mastering Sales Technique
- Business Communication
- Fundamentals of Journalism
- Economics Masterclass
- Free Courses
List vs Tuple: Difference Between List and Tuple
Updated on 21 May, 2024
227.46K+ views
• 20 min read
Table of Contents
Summary:
In this Article, you will learn the difference between List and Tuple.
List | Tuple |
It is mutable | It is immutable |
The implication of iterations is time-consuming in the list. | Implications of iterations are much faster in tuples. |
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. |
Unexpected errors and changes can easily occur in lists. | Unexpected errors and changes rarely occur in tuples. |
Read more to know each in detail.
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.
You can also check out our free courses offered by upGrad under Javascript.
In the list vs tuple conversation there is one more thing, that is their modifying nature. The tuples cannot be modified whereas the lists can be modified. One of the reasons why the tuples are known to have a good memory is because of this non-modifying nature. The number of methods available in these two also differ such as tuples have 33 methods whereas the list has 46 available methods.
There is a difference in python tuple vs list and the syntax for both tuple and the list also differs such as, the items in tuples are surrounded by parentheses( ) and the items in lists are surrounded by square brackets [ ]. The list consumes more storage space than the tuples. Also, the creation and accessing of the lists is a slower process than the tuples.
The list and tuples are not the same and should not be considered same at all. There is a significant difference between these two. Apart from the mutability difference, their variable sizes are also different, the lists have a variable size whereas the tuples hav e affixed size.
Although there are many differences between list and tuple, there are some similarities too, as follows:
- The two data structures are both sequence data types that store collections of items.
- Items of any data type can be stored in them.
- Items can be accessed by their index.
The table below includes the basic difference between list and tuple in Python.
Check out our Data Science Courses created for working professionals.
Before jumping to Python tuple vs. list differentiation, let’s find out what exactly these two are.
Lists
A list is one of the major Python data structures used to contain a setlist of things called items. Like arrays, list to tuple Python helps keep similar types of data values together, condensing their code together. This helps perform several detailed operations on multiple values at the same time. For example, a folder of songs on your desktop has different other subfolders adjusted following different genres for a hassle-free collection. List to tuple Python is used to improve efficiency and help the system manage all the values together.
Combining science with other areas helps you learn different things and opens up new science students’ career options. For example, mixing science with business could help you start a science-related business or manage a scientific company. These combined courses give you more skills and let you explore different job paths.
Tuples
Just like lists, tuples also contain a set of objects in an ordered manner. These objects are kept separated by commas. Tuples are immutable and do not allow the entrance of additional objects once a tuple is created. Tuples are incapable of expanding or making modifications; therefore, they differ from lists. Removing elements is also not possible from tuples which restrict its collection. The immutability often serves as an advantage in delivering faster, efficient results.
Some important features of Tuples include:
- Immutability: Once created, tuples cannot be changed. This means you can’t add, remove, or modify the elements in a tuple.
- Order preservation: Like lists, tuples keep the order of elements intact. This allows us to access elements by their position in the tuple.
- Indexing: Elements in a tuple can be accessed using their positions, starting from 0.
- Versatility: Tuples can contain different data types, making them useful for grouping related information.
- Data integrity: Since tuples are immutable, the data stored in a tuple remains unchanged throughout the program. This guarantees the integrity of your data.
- Function return values: Tuples are commonly used to return multiple values from a function. Each value corresponds to an element within the tuple.
- Memory efficiency: Tuples are generally more memory-efficient than lists. This makes them a good choice when you don’t need to modify the data.
Real-Life Applications of Tuple in Python
Here are a few everyday applications of tuples:
- Tuples can be used to store multiple items in a single variable – for example, storing coordinates of a point in a 2D space (x, y) or in a 3D space (x, y, z).
- Tuples are often used in dictionary keys in Python, as they are immutable, ensuring the integrity of the key-value pairs in the dictionary.
- They are commonly used where an immutable sequence of data is required, such as a week of days or a set of system-defined colors.
- In database operations, tuples are used for handling returned rows of data since each row typically contains multiple fields.
- Function arguments and return values often use tuples to transport multiple values or grouped data.
While the major purpose and foundation of tuple vs. list Python are the same, various methods differentiate the two. Here’s what you will find in this Python tuple vs. list blog!
List And Tuples In Python: Syntax
List Syntax
The [ ] symbol initiates a list. Here is a syntax representing how to declare a list in Python.
num_list = [1,2,3,4,5]
print(num_list)
alphabets_list = [‘a’,‘b’,‘c’,‘d’,‘e’]
print(alphabets_list)
Finding different types of data within a list is something common. However, to initiate it, do as follows:
mixed_list = [‘a’, 1,‘b’,2,‘c’,3,‘4’]
print(mixed_list)
Furthermore, one can create a nested list (a list within a list) in Python as well. Here’s how:
nested_list = [1,2,3,[4,5,6],7,8]
print(nested_list)
Tuple Syntax
The () symbol initiates a tuple. Here is a syntax representing how to declare a tuple in Python
num_tuple = (1,2,3,4,5)
print(num_tuple)
alphabets_tuple = (‘a’,‘b’,‘c’,‘d’,‘e’)
print(alphabets_tuple)
A Tuple consists of data of different types. However, follow this syntax to initiate it:
mixed_tuple = (‘a’, 1,‘b,’ 2,‘c,’ 3, ‘4’).
print(mixed_tuple)
Also, one can create a nested tuple in Python as well. Here’s how:
nested_tuple = (1,2,3,(4,5,6),7,8)
print(nested_tuple)
Tuples and List in Python: Syntax Differences
Objects are stored in containers called lists and tuples. However, there are differences in both its use cases and syntax. Tuples are enclosed by round brackets () and lists by square brackets []. Here’s how to create a list and tuple in python.
list_numbers = [1,2,3,4,5]
tuple_numbers = (1,2,3,4,5)
print(list_numbers)
print(tuple_numbers)
To check any object’s data type, use the type function.
type(list_numbers)
type(tuple_numbers)
List vs Tuple
Python’s most widely used build-in data types Python list vs. tuple are hard to differentiate between considering many similarities they both emit, confusing Python beginners in using the most appropriate one. Here’s how you can differentiate between Python tuple vs. list.
The table below includes the basic difference between list and tuple in Python.
List | Tuple |
It is mutable | It is immutable |
The implication of iterations is time-consuming in the list. | Implications of iterations are much faster in tuples. |
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. |
Unexpected errors and changes can easily occur in lists. | Unexpected errors and changes rarely occur in tuples. |
Learn more about free online python course for beginners here!
The following sections provide a detailed version of the list vs tuple for better understanding.
Our learners also read: Excel online course free!
upGrad’s Exclusive Data Science Webinar for you –
Transformation & Opportunities in Analytics & Insights
Difference in syntax
Tuple vs. list Python syntax has a very slight difference between the two but is essential for the right implementation. One major obvious difference between Python list vs. tuple is list syntax uses a square bracket, while the tuple syntax is surrounded using parentheses. As mentioned in the introduction, the syntax for list and tuple are different. For example:
list_num = [10, 20, 30, 40]
tup_num = (10, 20, 30, 40)
Also, check out our business analytics course to widen your horizon.
Mutability
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable. This means that in list vs. tuple Python lists can be changed after it is created to comply with requirements, while tuples cannot be changed or altered after their creation following your required edits, causing tuples to have a fixed size.
So, some operations can work on lists, but not on tuples. For example, in data science, if a list already exists, particular elements of it can be reassigned. Along with this, the entire list can be reassigned. Elements and slices of elements can be deleted from the list.
On the other hand, particular elements on the tuple cannot be reassigned or deleted, but it is possible to slice it, and even reassign and delete the whole tuple. Because tuples are immutable, they cannot be copied.
An item in the list can be changed, it can be accessed directly. The items in the list can be changed by using the indexing operator [ ]. The individual values can also be changed in the lists.
Check out: Python vs Java
Explore our Popular Data Science Courses .
Operations
Although there are many operations similar to both lists and tuples, lists have additional functionalities that are not available with tuples. These are insert and pop operations, and sorting and removing elements in the list.
There are many operators such as
Operator | Purpose |
The + operator | returns a tuple that contains the first and the second tuple object. |
The [ ] operator | This returns the item at the given index. |
The * operator | This concatenates many copies of a tuple. |
The [: ] operator | Returns the item in a specific range, the two index operands are separated by the :: symbol. |
Mutable List vs. Immutable Tuples
In Python, both lists and tuples allow you to perform various operations, like accessing specific elements, taking out parts, joining them together, and more. However, because lists can be changed and tuples cannot, the operations you can perform on them vary.
Python Indexing
Lists and tuples both let you access specific elements by their index, starting from 0. It’s a straightforward and effective way to retrieve data from these data structures.
my_list = [1, 2, 3]
my_tuple = (4, 5, 6)
print(my_list[0]) # Output: 1
print(my_tuple[1]) # Output: 5
Python Slicing
Slicing can be used to extract a specific subset of elements from both lists and tuples easily.
my_list = [1, 2, 3, 4, 5]
my_tuple = (6, 7, 8, 9, 10)
print(my_list[1:3]) # Output: [2, 3]
print(my_tuple[:3]) # Output: (6, 7, 8)
Python Concatenation
Use the “+” operator to combine both lists and tuples. It’s a simple and straightforward way to concatenate them.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
tuple1 = (7, 8, 9)
tuple2 = (10, 11, 12)
print(list1 + list2) # Output: [1, 2, 3, 4, 5, 6]
print(tuple1 + tuple2) # Output: (7, 8, 9, 10, 11, 12)
Python Append
To add new elements to a list, simply use the append() method.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
Python Extend
You can add more items to a list using the extend() method and another list.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
Python Remove
Use the remove() method to remove elements from lists easily.\
my_list = [1, 2, 3, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 4]
Functions
Some of the Python functions can be applied to both data structures, such as len, max, min, any, sum, all, and sorted.
Description of some the functions are mentioned below-
- max(tuple) → Returns item from the tuple with the max value.
- min(tuple) → Returns item from the tuple with the min value.
- tuple(seq) → Converts a list into tuple.
- cmp(tuple1, tuple2) → Compares the elements of both the mentioned tuples
Python Expression | Description |
len | Length |
(1,2) + (3,4) | Concatenation |
2 in (1,2,3) | Membership |
(‘Morning’,) * 2 | Repetition |
Must read: Data structures and algorithms free course!
List Functions
[‘__doc__’,’__eq__’,’__format__’, ‘__get__’,’__getattribute__’,’__getitem_’ ‘__gt__’,’__hash__’,’__iadd__’,’__imul__’,’__init__’,’__init_subclass__”__iter__’,’__le__’,’__len__’,’__lt__’,’__mul__’, ‘__ne__’,’__new__’,
‘__reduce__’, ‘__reduce_ex__’,’__repr__’,’__reversed__’,’__rmul__’,’__setattr__’,’__setitem__’,’__sizeof__’,’__str__’,’__subclasshook__’,
‘append’,
‘clear’,
‘copy’,
‘count’,
‘extend’,
‘index’,
‘insert’,
‘pop’,
‘remove’,
‘reverse’,
‘sort’]
Tuple Functions
[‘__add__’,
‘__class__’,
‘__contains__’,
‘__delattr__’,
‘__dir__’,
‘__doc__’,
‘__eq__’,
‘__format__’,
‘__ge__’,
‘__getattribute__’,
‘__getitem__’,
‘__getnewargs__’,
‘__gt__’,
‘__hash__’,
‘__init__’,
‘__init_subclass__’,
‘__iter__’,
‘__le__’,
‘__len__’,
‘__lt__’,
‘__mul__’,
‘__ne__’,
‘__new__’,
‘__reduce__’,
‘__reduce_ex__’,
‘__repr__’,
‘__rmul__’,
‘__setattr__’,
‘__sizeof__’,
‘__str__’,
‘__subclasshook__’,
‘count’,
‘index’]
Size
The lengths of tuples and lists differ. Tuples have a fixed length, while lists can vary in size. This means lists can have different sizes but not tuples.
In Python, tuples are allocated large blocks of memory with lower overhead, since they are immutable; whereas for lists, small memory blocks are allocated. Between the two, tuples have smaller memory. This helps in making tuples faster than lists when there are a large number of elements.
In simple terms, the size would mean the amount of memory a tuple is storing if it is small or large memory. The size can be calculated using the built-in len() function.
Example:
a= (1,2,3,4,5,6,7,8,9,0)
b= [1,2,3,4,5,6,7,8,9,0]
print(‘a=’,a.__sizeof__())
print(‘b=’,b.__sizeof__())
Output:
a=104
b=120
Also, visit upGrad’s Full Stack Bootcamp page for all undergraduate and postgraduate programs.
In list vs. tuple Python has to provide an extra memory block to lists as it is expandable and might require it with potential modifications.
Efficiency
Tuples are more memory efficient than lists because they have fewer built-in operations. While lists are suitable for a smaller number of elements, tuples are faster when dealing with large amounts of data.
Example:
A = (‘Name = Ash Ketchum’,’Grade = 8′,’ID = 101′, ‘Address = Tokyo’)
B = [‘Apples’, ‘Mangoes’, ‘Grapes’, ‘Bananas’]
print(‘Size of tuple :’,A.__sizeof__())
print(‘Size of list :’,B.__sizeof__())
Output:
Size of tuple : 28
Size of list : 36
Type of elements
Elements belonging to different data types, i.e., heterogeneous elements, are usually stored in tuples. While homogeneous elements, elements of the same data types, are usually stored in lists. But this is
not a restriction for the data structures. Similar data type elements can be stored in tuples, and different data type elements can also be stored in lists.
Top Data Science Skills to Learn to upskill
Length
Lengths differ in the two data structures. Tuples have a fixed length, while lists have variable lengths. Thus, the size of created lists can be changed, but that is not the case for tuples.
Methods
The methods that apply only to lists in Python are, insert(), clear(), sort(), pop(), reverse(), remove(), and append(). While these methods are only applicable to lists, a few more are shared by both lists and tuples. These include count() and index() methods.
Debugging
When it comes to debugging, in lists vs tuples, tuples are easier to debug for large projects due to its immutability. So, if there is a smaller project or a lesser amount of data, it is better to use lists. This is because lists can be changed, while tuples cannot, making tuples easier to track.
Nested lists and tuples
Tuples can be stored in lists, and likewise, lists can be stored inside tuples. In nested tuples, a tuple can hold more tuples and might extend in more than two dimensions. On the other hand, in nested lists, a list can hold more lists in countless dimensions as you wish.
Uses
It is important to understand that there are different cases where it is better to use one of these data structures, such as; using either one depends on the programmer, i.e., choosing one based on whether they want to change the data later or not.
Tuples can be used as equivalent to a dictionary without keys to store data. When tuples are stored within lists, it is easier to read data. Meanwhile, lists can be used to contain similar resembling elements. Tuples are comparatively more time and memory efficient than lists with restricted usage. However, the lists’ immutability makes it efficient to align with potential changes effectively.
Read: More types of data structures in Python
List And Tuple In Python: Use Cases
The following scenarios call for data storage that works best for Python’s lists:
- Lists can hold a variety of data kinds, and you can retrieve them using the index of the list.
- Lists are useful for performing computations on a collection of elements since Python enables you to do so directly on the list.
- It is simple to expand or decrease the size of your list as necessary if you are unsure how many elements will be kept in it in advance.
The following scenarios lend themselves to the use of Python’s tuples for data storage:
- When you are certain of the precise data that will be entered into an object’s fields, it is ideal to use a tuple.
- You can use a tuple, for instance, to store login information for your website.
- tuples can only be used as dictionary keys because they are immutable (unchangeable).
- However, you must convert a list into a tuple before using it as a key.
Tuples as Dictionary Keys
In Python, only immutable objects can be used as keys in dictionaries. Tuples, being immutable, can, therefore, be used as keys.
For example:
python
tuplekey = {}
tuplekey[(‘blue’, ‘sky’)] = ‘Good’
tuplekey[(‘black’,’blood’)] = ‘Bad’
print(tuplekey)
We have a dictionary named `tuplekey`. The keys are tuples `(‘blue’, ‘sky’)` and `(‘black’,’blood’)`, and their corresponding values are ‘Good’ and ‘Bad’. When we print `tuplekey`, the output will be `{(‘blue’, ‘sky’): ‘Good’, (‘black’, ‘blood’): ‘Bad’}`.
Tuple Packing and Unpacking
Tuple packing lets us assign multiple values to a tuple in a single statement.
For example:
python
person = (“Rahul”, ‘6 ft’, “Manager”)
print(person)
Here, we create a tuple `person` that contains three elements. When we print `person`, the output will be `(“Rahul”, ‘6 ft’, “Manager”)`.
Tuple unpacking is the opposite process, where we assign the values of a tuple to separate variables.
For example:
python
person = (“Rahul”, ‘6 ft’, “Manager”)
(name, height, profession) = person
print(name)
print(height)
print(profession)
In this case, we unpack `person` into three variables: `name`, `height`, and `profession`. The print statements will output ‘Rahul’, ‘6 ft’, and ‘Manager’, respectively.
List vs Tuple in Python: Which One is Superior?
To see whether Python Tuple or Python List serves us better, we will compare their performance by running some operations.
Based on memory efficiency
When it comes to memory usage, tuples are advantageous because they are stored in a single memory block. This means they do not require additional space for new objects.
On the other hand, lists are allocated in two separate blocks. The first block contains Python object information, while the second block is for the actual data, and its size can vary.
custom_list = []
custom_tuple = ()
custom_list_elements = [“Element1”, “Element2”, “Element3”]
custom_tuple_elements = (“Element1”, “Element2”, “Element3”)
print(sys.getsizeof(custom_list))
print(sys.getsizeof(custom_tuple))
In terms of iterations
For the same reasons stated above, this storage design makes tuples faster compared to lists.
custom_list = list(range(100000001))
custom_tuple = tuple(range(100000001))
start_time_tuple = time.time_ns()
for element in custom_tuple:
a = element
end_time_tuple = time.time_ns()
print(“Total lookup time for Custom Tuple: “, end_time_tuple – start_time_tuple)
start_time_list = time.time_ns()
for element in custom_list:
a = element
end_time_list = time.time_ns()
print(“Total lookup time for Custom List: “, end_time_list – start_time_list)
Output:
Total lookup time for Tuple: 7038208700
Total lookup time for LIST: 19646516700
Tuples Over Lists: When To Use It?
Although Lists and Tuple in Python ensures holding sets of data effortlessly, they both are distinct in many ways. However, there are certain circumstances where using Tuples over Lists would be a better decision. These scenarios are as follows:
- Immutable Data: Since tuples cannot have their contents modified after they have been produced, they are immutable. Given this, Tuples emerge as a better choice for storing data, such as setup parameters, constants, or other data, that mustn’t undergo modifications and remain consistent when the application is running.
- Performance: Due to their immutability, tuples are more compact than lists and may be quicker to create, access, and loop over. If you have a sizable amount of data you must regularly store, access, and use but doesn’t require to be changed, utilizing a tuple may be more efficient than using a list.
- Data Integrity: Tuples are a useful tool for maintaining data integrity since they guarantee that the data’s structure and contents remain constant. If a function returns a certain number of values, for example, you may intend to return them as a tuple rather than a list so the caller knows how much data to expect.
Read our popular Data Science Articles
Conclusion
In this article we have discussed about difference between list and tuple and understood about them. This article helps in understanding the differences between lists and tuples. Even though both types are data structures in Python, it is important to be familiar with these differences when making a choice. The most important differences to keep in mind is that lists are mutable, and tuples are not, lists have variable sizes and tuples have fixed sizes. Lastly, operations in tuples can be executed faster.
If you are reading this article, most likely you have ambitions towards becoming a Python developer. If you’re interested to learn python & want to get your hands dirty on various tools and libraries, check out IIIT-B & upGrad’s Executive PG Programme in Data Science.
Frequently Asked Questions (FAQs)
1. When is a Python list preferred for storing data?
Python list is considered to be the best data structure to store the data in the following scenarios: A list can be used to store various values with different data types and can be accessed just by their respective indices. When you need to perform mathematical operations over the elements, a list can be used since it allows you to mathematically operate the elements directly. Since a list can be resized, it can be used to store the data when you are not certain about the number of elements to be stored.
2. State the various operations of namedtuple.
The namedtuple in Python performs various operations. The following is a list of some of the most common operations performed by the namedtuple - Access by index, Access by key name, make(), _asadict(), using “**” (double star) operator, _fileds(), _replace(), etc.
3. What are the different ways of creating a list?
A Python list can be created in multiple ways that are mentioned here. Using for loops - A for loop is the most elemental way of creating a list. A list can be created using a for loop in three simple ways - Create an empty list, Iterate over all the elements that are to be inserted, Append each element in the list using the append() function. Using map(): The map() function in Python can be used alternatively to create a list. This function accepts two parameters - Function: The function to which the map passes each iterable and Iterable: The element or the iterable to be mapped. Using List comprehensions: This method is the most optimized of all three methods. While in the above methods an empty list has to be created first, list comprehensions allow you to insert all the elements in a list using a single line.
4. What is the difference between list and set?
Lists and Tuples are standard data types that stores the data in Python. The data is stored in a sequential manner. Sets also store data types in Python. The difference between these two would be the multiple occurrences. Lists can have duplicates as it can have multiple occurrences whereas the set cannot have duplicates or multiple occurrences.
5. What is a list used for?
Lists are useful when the related values are into consideration. They store multiple items in a single lace. This eventually helps in keeping the data together and perform many functions. Alogwith the other things, lists are also useful to allow duplicates, and are mutable. Once an item in the list is created later it can be changed by either addition or deletion.
6. What is the basic difference between tuple and dictionary explain with example?
The difference lies in the number of values both can contain within themselves. The tuple contains a set of predefined numbers of values whereas, the dictionary does not have any such limitation. Tuple has values contained in an ordered manner whereas th dictionary has the unordered collection.
7. Why is dictionary faster than the list Python?
The reason for the dictionary being faster than the list is because of lookup. Dictionary has lookup capabilities which is implemented using the hash tables in Python. Whereas, the list is an iteration.So to bear the results in list, a wak through the list would be required until the results come across.
8. Which is better list or dictionary in Python?
From the speed perspective, the dictionary would be considered as better. As it is faster because of the has lookup feature. The hash lookup is what makes dictionary faster which list does not have. The list requires a walk through until the results are found.
9. What is the difference between mutable and immutable?
Mutablity shows the abiotic to change. In the context of python, if the value can change then it is considered as mutable. And if the value cannot change then it would be considered as immutable.
10. What is the difference between a tuple and a list?
Lists are mutable and use square brackets ([]), while tuples are immutable and use parentheses (()). Lists allow modifications, whereas tuples do not.
Did you find this article helpful?
Our Trending Courses
MS in Data Science Post Graduate Programme in Data Science & AI (Executive) DBA in Emerging Technologies with concentration in Generative AIOur Trending Skill
Data Analysis Inferential Statistics Logistic Regression Linear Regression Linear Algebra for Analysis Hypothesis TestingGet Free Consultation
By clicking "Submit" you Agree toupGrad's Terms & Conditions
FREE COURSES
Start Learning For Free