Difference between python list and tuple

5 Major Difference Between List and Tuple in Python

Tuple and List are the very important data structures in Python to store the series of data. In this post, I am demonstrating the difference between list and tuple in Python.

If you are a new Python programmer, let me tell you, it is a collection object like an array in C, C++ programming. An array is far different from list and tuple. You will realize this at the end of this article.

In Python, having two data structures (List and Tuple) with a slight difference is more confusing for the Python programmer. But in context to the use cases of both, they are distinct and both have their advantages and disadvantages.

This is one of the most common Python interview questions asked in many of the interviews.

Let’s start digging without wasting any time…

Difference between List and Tuple in Python:

I am trying to make it simple with examples for you.

1. Syntax

The syntax for the list and tuple are slightly different.

Python List Example:

listWeekDays = ['mon', 'tue', 'wed', 2]

You can check the type of object created using type() function in Python.

Python Tuple Example:

tupWeekDays = ('mon', 'tue', 'wed', 2)

Using type() function to check the tupWeekDays type.

list and tuple example in python

If you look into the above code…

Tuple uses ( and ) to bind the elements where a list uses [ and ] to bind the elements in the collection.

You can even create tuple without ( and ) operators. Comma operator ( , ) is mandatory to distinguish elements in a tuple.

tupWeekDays = 'mon', 'tue', 'wed', 2

When you want to create an empty tuple, you can not create it without ( and ) operators. The only ways are…

It’s very rare you will use an empty tuple as it is immutable and you can not add elements once it is created.
If you don’t know what is an immutable data structure, here you go…

2. Mutability Vs Immutability

A tuple is a list that one cannot edit once it is created in Python code. The tuple is an immutable data structure.

Whereas List is the mutable entity. You can alter list data anytime in your program.

Among all, this is the major difference between these two collections. I was asked in Druva interview questions, why tuple is immutable.

It is easy to demonstrate the mutability difference between tuple and list in Python with an example.

>>> tupWeekDays = ('mon', 'tue', 'wed', 2) >>> print(tupWeekDays) ('mon', 'tue', 'wed', 2) >>> tupWeekDays(2)='fri' Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment

tuple is immutable in Python

>>> tupWeekDays = ['mon', 'tue', 'wed', 2] >>> print(listWeekDays) ['mon', 'tue', 'wed', 2] >>> listWeekDays[2]='fri' >>> print(listWeekDays) ['mon', 'tue', 'fri', 2]

list is mutable in Python

For more clarification, you must read the difference between mutable and immutable. There, I have explained, why tuple is immutable with more examples in a better way.

3. Functionality

There are more functions are associated with List than Tuple.

You can use a dir([object]) inbuilt function to get all the associated functions for list and tuple.

Simply create a tuple and list. Pass these objects to dir function. You get a list of the associated functions as below.

>>> tupWeekDay=('mon', 'mon', 'wed', 2) >>> dir(tupWeekDay) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get slice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__ lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__' , '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count ', 'index'] >>> listWeekDay=['mon', 'mon', 'wed', 2] >>> dir(listWeekDay) ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli ce__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getit em__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__r educe__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__' , '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'a ppend', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort' ]

You can clearly see that, there are so many additional functionalities associated with a list over a tuple. You can do insert and pop operation, removing and sorting elements in the list with inbuilt functions.

Some List Functionality examples you would like to give a try…

In tuple, there is no index placed for each element. So you can not do the insert, pop, remove or sort elements. Moreover, it is an immutable data type so there is no way to change the elements in a tuple.

4. Python List of Tuples:

How to create a list as a collection of tuples?

As you know everything in Python is an object (including the tuple and list). The list is a collection of objects.

So you can create a list of tuple objects; code as given below.

listWeekDay=[('mon', 'tue', 'wed'),('sat','sun')]

In the above example, days in the list are separated as tuples, based on weekdays and week off days.

5. Where to use Tuple and List?

If you are writing a program where you need a collection of objects, you have two choices- Tuple vs List.

Sometimes in the program, you may need elements in the collection that can be alerted at any time. You must use a list instead of a tuple.

You can also take keyboard input from the user and insert a new element in a List.

So, what is the advantage of using tuples over lists?

A tuple is immutable in Python and you can not change its elements once it is created. If you are creating collections and elements in the collection are not going to change, you must use Tuple.

In case if you tried to alter the tuple value, it will throw an error. So it prevents the value from changing.

Note: All the above-demonstrated examples are executed and tested on Python 2.7 and it will run on Python 3 as well. For every example, I have a clear python interpreter console and executed to avoid the mess.

These are all the difference between list and tuple in Python. If you have any thoughts on these, write in a comment.

Источник

Python List vs. Tuple

difference between list and tuple in python

difference between list and tuple in python

В этой статье будет рассмотрена разница между списком и кортежем (List vs. Tuple).

List и Tuple в Python — это классы структур данных Python. Список является динамическим, тогда как кортеж имеет статические характеристики. Это означает, что списки могут быть изменены, тогда как кортежи не могут быть изменены, кортеж быстрее списка из-за статичности по своей природе. Списки обозначаются квадратными скобками, а кортежи обозначаются скобками.

Важные различия между List и Tuple в Python

List (список) Tuple (Кортеж)
1 Списки изменяемы Кортежи неизменны
2 Последствия итераций отнимают много времени Последствия итераций сравнительно быстрее
3 Список лучше подходит для выполнения операций, таких как вставка и удаление. Тип данных Tuple подходит для доступа к элементам
4 Списки потребляют больше памяти Кортеж потребляет меньше памяти по сравнению со списком
5 Списки имеют несколько встроенных методов. Tuple не имеет большого количества встроенных методов.
6 Более вероятны непредвиденные изменения и ошибки В кортеже это трудно осуществить.

Список против кортежа

Проверим, являются ли кортежи неизменяемыми, а список изменяемым
Здесь мы собираемся сравнить тест изменчивости списка и кортежа.

# Creating a List with # the use of Numbers # code to test that tuples are mutable List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print("Original list ", List) List[3] = 77 print("Example to show mutablity ", List)

Результат выполнения кода:

Исходный список [1, 2, 4, 4, 3, 3, 3, 6, 5] Пример для демонстрации изменчивости [1, 2, 4, 77, 3, 3, 3, 6, 5]

Пример с кортежем: далее мы увидим, что кортеж не может быть изменен.

tuple1 = (0, 1, 2, 3) tuple1[0] = 4 print(tuple1)

Результат выполнения кода:

Traceback (most recent call last): File "tuple_example.py", line 3, in tuple1[0]=4 TypeError: 'tuple' object does not support item assignment

Проверка эффективности работы кортежей с памятью

Поскольку кортежи хранятся в одном блоке памяти, им не требуется дополнительное пространство для новых объектов, в то время как списки размещаются в двух блоках: первый фиксированный со всей информацией об объектах Python, а второй блок переменного размера для данных.

import sys a_list = [] a_tuple = () a_list = ["Lemons", "And", "Apples"] a_tuple = ("Lemons", "And", "Apples") print(sys.getsizeof(a_list)) print(sys.getsizeof(a_tuple))

Результат выполнения кода:

Проверка скорости итераций в Tuple по сравнению с List

import sys, platform import time l=list(range(100000001)) t=tuple(range(100000001)) start = time.time_ns() for i in range(len(t)): a = t[i] end = time.time_ns() print("Total lookup time for Tuple: ", end - start) start = time.time_ns() for i in range(len(l)): a = l[i] end = time.time_ns() print("Total lookup time for LIST: ", end - start)

Результат выполнения кода:

Общее время поиска для Tuple: 7038208700 Общее время поиска для LIST: 19646516700

Источник

Читайте также:  Http portal mkpnet ru iptv playlist php
Оцените статью