State one similarity and one difference between list and tuples

Differences and Similarities between Python Lists, Sets and Tuples.

State one similarity and one difference between list and tuples
Photo by Muhannad Ajjan on Unsplash

Lists, Sets and Tuples are data structures in python. They store values (like strings, numbers, even other lists, sets and tuples!). Their values are comma separated and enclosed in brackets.

Differences

  1. Perhaps the most popular difference is the type of brackets each data structure uses. Lists use square brackets, Sets use curly brackets and Tuples use the familiar round brackets.
>>> myList = [1, 2, 3]
>>> type(myList)
<class 'list'>
>>> myTuple = (1, 2, 3)
>>> type(myTuple)
<class 'tuple'>
>>> mySet = {1, 2, 3}
>>> type(mySet)
<class 'set'>

The type function tells the class of the argument passed into it. The type of brackets you enclose your values in pretty much defines what type of data structure you are creating.

2. Lists and Tuples are ordered data structures while Sets are unordered. In simple terms, if I were to create a set data structure, and I were to print out the results, the result would not be in the order I originally typed it in.

>>> fruits = {'apple', 'banana', 'cherry', 'date'}
>>> print(fruits)
{'cherry', 'banana', 'apple', 'date'}

Since sets are not ordered, items cannot be accessed in a set by indexing. Lists and Tuples do not change their order at all.

3. Lists and Sets are mutable, Tuples are immutable. This means that you cannot add new elements to a tuple. This can be seen by the absence of methods that can be used add new items to a tuple [e.g append(), extend(), add()]. Once a tuple is created, it cannot be changed or modified. There are ways around this problem though😏. One of such ways is to change the data structure from a tuple to a list, modify the list, then turn the list back to a tuple.

>>> small_numbers = (0, 1, 2, 3)
>>> edit_tuple = list(small_numbers)
>>> edit_tuple.append(4)
>>> small_numbers = tuple(edit_tuple)
>>> small_numbers
(0, 1, 2, 3, 4)
>>> type(small_numbers)
<class 'tuple'>

It should be noted that Lists can have its items modified and can also have items added to it. Sets can have items added to it but cannot have its items modified or changed.

4. Sets do not allow duplicate items, Lists and Tuples allow duplicate items. If a value in a set was written two or more times and printed out, the output would have only one of those duplicate values.

>>> colorList = ['red', 'orange', 'yellow', 'orange', 'red']
>>> colorTuple = ('red', 'orange', 'yellow', 'orange', 'red')
>>> colorSet = {'red', 'orange', 'yellow', 'orange', 'red'}
>>> colorList
['red', 'orange', 'yellow', 'orange', 'red']
>>> colorTuple
('red', 'orange', 'yellow', 'orange', 'red')
>>> colorSet
{'red', 'orange', 'yellow'}

5. Sets cannot hold mutable objects. for example, if you try to input a list in a set, you would get an error telling you that you are trying to put an unhashable type in the set. (unhashable means mutable basically).

>>> numbers = {1, 2, [3, 4, 5,], 6}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

What are the differences and similarities between tuples and lists in Python?

PythonServer Side ProgrammingProgramming

Both List and Tuple are called as sequence data types of Python. Objects of both types are comma separated collection of items not necessarily of same type.

List vs Tuple

The table below includes the basic difference between list and tuple in Python.

ListTuple
It is mutableIt 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.

The following sections provide a detailed version of list vs tuple for better understanding.

Difference in syntax

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)

Mutability

One of the most important differences between list and tuple is that list is mutable, whereas a tuple is immutable. This means that lists can be changed, and tuples cannot be changed.

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.

Check out:Python vs Java

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.

Functions

Some of the Python functions can be applied to both data structures, such as len, max, min, any, sum, all, and sorted.

Size

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.

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.

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.

Debugging

When it comes to debugging, inlists 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 in nested lists, a list can hold more lists.

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.

Read: More types of data structures in Python

The Key Difference between a List and a Tuple

The main difference between lists and tuples is the fact that lists are mutable whereas tuples are immutable.

What does that even mean, you say?

A mutable data type means that a python object of this type can be modified.

An immutable object can’t.

Let’s see what this means in action.

Let’s create a list and assign it to a variable.

>>> a = ["apples", "bananas", "oranges"]

Now let’s see what happens when we try to modify the first item of the list.

Let’s change “apples” to “berries”.

>>> a[0] = "berries" >>> a ['berries', 'bananas', 'oranges']

Perfect! the first item of a has changed.

Now, what if we want to try the same thing with a tuple instead of a list? Let’s see.

>>> a = ("apples", "bananas", "oranges") >>> a[0] = "berries" Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment

We get an error saying that a tuple object doesn’t support item assignment.

The reason we get this error is because tuple objects, unlike lists, are immutable which means you can’t modify a tuple object after it’s created.

But you might be thinking, Karim, my man, I know you say you can’t do assignments the way you wrote it but how about this, doesn’t the following code modify a?

>>> a = ("apples", "bananas", "oranges") >>> a = ("berries", "bananas", "oranges") >>> a ('berries', 'bananas', 'oranges')

Fair question!

Let’s see, are we actually modifying the first item in tuple a with the code above?

The answer is No, absolutely not.

To understand why, you first have to understand the difference between a variable and a python object.

Difference between List and Tuples in Python

Contents

  • 1 Difference between List and Tuples in Python
    • 1.1 Comparison between List and Tuples in Tabular Form
    • 1.2 Comparison Chart
    • 1.3 List
      • 1.3.1 Example of List:
    • 1.4 Tuples
      • 1.4.1 Syntax of Tuples
      • 1.4.2 Example of Tuples
  • 2 More Difference

Comparison between List and Tuples in Tabular Form

  • ListsandTuples are very important data structures in Python.
  • The Key Difference between List and Tuples is that the List iswritten in square brackets [ ] while Tuples are written in round brackets ( ).
  • Also, List is Mutable and Tuple is immutable.
  • In Python List is just like an array.
State one similarity and one difference between list and tuples
List and Tuples Difference

Comparison Chart

ListTuples
1List is mutableTuples are immutable
2List iteration is slower and time-consuming.Tuples iteration is faster.
3List is performed well in insertion and deletion operations.Tuples are performed well in accessing elements operations.
4List takes more memoryTuples take less memory.
5Lists are many built-in methodsTuples are less in-built methods.
6In List Error is more likely to happen.In Tuples Error hardly takes place.
7Lists can be used to store homogeneous and heterogeneous elements.Tuples are used to store only heterogeneous elements.




List

  • Syntax of List:
    • list_num = ['1', '2', '3, '4', '5']
  • Example of List:

    • list_num = ['1', '2', '3','4','5'] print(list_num)
    • Output: [‘1’, ‘2’, ‘3’, ‘4’, ‘5’]

Tuples

  • Syntax of Tuples

    • tuple_num = ('1', '2', '3', '4', '5')
  • Example of Tuples

    • tuple_num = ('1', '2', '3', '4', '5') print(tuple_num)
    • Output: (‘1’, ‘2’, ‘3’, ‘4’, ‘5’)