CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

11 April, 2022

Python List Vs Tuple

 Programing Coderfunda     April 11, 2022     Python     No comments   

Python List Vs Tuple

In this tutorial, we will learn the important difference between the list and tuples and how both are playing a significant role in Python.

Lists and Tuples are used to store one or more Python objects or data-types sequentially. Both can store any data such as integer, float, string, and dictionary. Lists and Tuples are similar in most factors but here we will describe the main difference between them.

Let's discuss the main differences in the following points.

Representation Differences

The representation of the Lists and tuple is marginally different. List are commonly enclosed with the square bracket [], and elements are comma-separated element. Tuples are enclosed with parenthesis (), and elements are separated by the comma. The parenthesis is optional to use, and these types of tuples are called tuple packing.

Consider the following example.

  1. list1 = ['JavaTpoint', 1, 2, 54.30, {'Name: ''Peter'}]  
  2. print(type(list))  
  3. tuple1 = ('JavaTpoint',5,8,31.9,[1,2,3])  
  4. print(type(tuple1))  

Output:

<class 'list'>
<class 'tuple'>

In the above program, we defined a list1 variable which holds a list of different data type from index 0 to 4. We defined another variable tuple1, which holds a tuple of different data types. It is enclosed by the ().

Mutable Lists and Immutable Tuples

It is the most important difference between list and tuple whereas lists are mutable, and tuples are immutable. The lists are mutable which means the Python object can be modified after creation, whereas tuples can't be modified after creation. Consider the given an example.

  1. a = ["Peter","Joseph","Mathew","Ricky"]  
  2. print(a)  

Output:

['Peter', 'Joseph', 'Mathew', 'Ricky']

Now we are changing 0th index element "Peter" to "Samson".

  1. a[0] = "Samson"  
  2. print(a)  

Output:

['Samson', 'Joseph', 'Mathew', 'Ricky']

Now we create a tuple and do the same thing.

  1. a = (10,20,"JavaTpoint",30,40)  
  2. print(a)  

Output:

(10, 20, 'JavaTpoint', 30, 40)

  1. a[0] = 50  

Output:

TypeError                                 Traceback (most recent call last)
<ipython-input-5-52b2981fae12> in <module>
----> 1 a[0] = 50

TypeError: 'tuple' object does not support item assignment

We get an error while changing the 1st element of the tuple because of immutability. It does not support item assignment.

Debugging

The tuples are easy to debug in a big project because of its immutability. If we have a small project or less number of data, then lists play an effective role. Let's consider the following example:

  1. a = [6,9,4,3,7,0,1]  
  2. # Copying address of a in b  
  3. b = a  
  4. a[3] = "JavaToint"  
  5. print(a)  

Output:

[6, 9, 4, 'JavaToint', 7, 0, 1]

In the above code, we did b = a; here we are not copying the list object from b to a. The b referred to the address of the list a.  It means if we make the change in the b then that will reflect the same as in list a, and it makes debugging easy. But it is hard for the significant project where Python objects may have multiple references.

It will be very complicated to track those changes in lists but immutable object tuple can't change after created.

So tuples are easy to debug.

Functions Support

The tuples support less operation than the list. The inbuilt dir(object) is used to get all the supported functions for the list and tuple.

  • List Functions
  1. dir(list)  

Output:

['__add__','__class__','__contains__','__delattr__','__delitem__','__dir_,
 '__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
  1. dir(tuple)  

Output:

['__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']

Memory Efficient

The tuples are more memory efficient than the list because tuple has less built-in operations. Lists are suitable for the fewer elements whereas tuples are a bit faster than the list for the huge amount of data.

  1. Tuple = (1,2,3,4,5,6,7,8,9,0,5485,87525,955,3343,53234,6423,623456,234535)  
  2. List = [1,2,3,4,5,6,7,8,9,0,78,34,43,32,43,55,54,212,642,533,43434,54532 ]  
  3. print('Tuple size =', Tuple.__sizeof__())       # Tuple size = 52  
  4. print('List size =', List.__sizeof__())    

Output:

Tuple size = 168
List size = 216

Conclusion

  • In Some cases, lists might seem more useful than tuples. But tuples are important data structures of the Python. Tuples are commonly used for unchangeable data or we can say that the data will be "write- protected" in the tuples. Tuples sends the indication to the Python interpreter the data should not change in the future.
  • We can use tuple the same as a dictionary without using keys to store the data. For example-
  1. list1 = [(101, "Mike", 24),(102, 'Hussey', 26),(103, 'David', 27),(104,  'Warner', 29)]  
  • Tuples can use for the dictionary keys because these are hashable and immutable whereas lists can't use a keys in dictionary.
  1. dict = {("Mike",22):24000}    #valid dictionary  
  2. dict = {["Peter",26]:25000}   #Invalid dictionary  
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Python FunctionPython FunctionFunctions are the most important aspect of an application. A function can be defined as the organized block of reusable code, which can… Read More
  • Python Built-in FunctionsPython Built-in FunctionsThe Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The python interpret… Read More
  • Python DictionaryPython DictionaryPython Dictionary is used to store the data in a key-value pair format. The dictionary is the data type in Python, which can simulate… Read More
  • Python SetPython SetA Python set is the collection of the unordere items. Each element in the set must be unique, and immutable, and the sets remove the duplica… Read More
  • Python abs() FunctionPython abs() FunctionThe python abs() function is used to return absolute value of a number. It takes only one argument, a number whose abso… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Write API Integrations in Laravel and PHP Projects with Saloon
    Write API Integrations in Laravel and PHP Projects with Saloon Saloon  is a Laravel/PHP package that allows you to write your API integratio...
  • Features CodeIgniter
    Features CodeIgniter There is a great demand for the CodeIgniter framework in PHP developers because of its features and multiple advan...
  • Laravel Breeze with PrimeVue v4
    This is an follow up to my previous post about a "starter kit" I created with Laravel and PrimeVue components. The project has b...
  • Fast Excel Package for Laravel
      Fast Excel is a Laravel package for importing and exporting spreadsheets. It provides an elegant wrapper around Spout —a PHP package to ...
  • Send message via CANBus
    After some years developing for mobile devices, I've started developing for embedded devices, and I'm finding a new problem now. Th...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Manipulate Image URLs in Laravel with the Image Transform Package - 6/19/2025
  • Handle Nested Arrays Elegantly with Laravel's fluent() Helper - 6/18/2025
  • Laravel 12.19 Adds a useEloquentBuilder Attribute, a FailOnException Queue Middleware, and More - 6/18/2025
  • Test Deferred Operations Easily with Laravel's withoutDefer Helper - 6/18/2025
  • Larallow is a Permissions Package With Support for Scopes - 6/17/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda