Quantcast
Channel: Like Geeks
Viewing all articles
Browse latest Browse all 104

Lists VS Tuples in Python

$
0
0

Python introduces four built-in data types that let you hold a collection of objects or values: list, tuple, dictionary, and set.

These are arguably the most versatile data structures that can store heterogeneous collections of Python objects. List and tuples fall into the category of sequence data types.

They allow you to store data in containers and retrieve it in an efficient manner. In this tutorial, we’ll see lists VS tuples in action.

 

 

Lists

Lists are a type of sequence that allows you to store a collection of homogenous or heterogeneous objects. In character, these are akin to what arrays are in any programming language.

Although, they are much more flexible than arrays. A list is a mutable sequence, which means that the objects or items stored inside it can be changed.

It can contain an arbitrary number of items. It grows as needed to accommodate new items and shrinks as items are removed.

You can create a list in Python by using square brackets:

my_list = []

To add items to your list, you need to separate them using commas.

my_list = ['hi', 'world', 1, 2, 3]

You can also construct a list using the list() constructor and optionally passing an iterable to it.

my_list = list((1, 2, 3))

Create List

Python provides us with a lot of functions to deal with lists as we’ll see later.

 

Tuples

Tuples belong to the type of sequence that is immutable. Just like lists, they let you store a collection of homogenous or heterogeneous objects.

However, the immutability feature means that objects or items stored inside a tuple can not be changed. Tuples are fixed-length data structures.

They are allocated large blocks of memory, which makes them faster than lists.

You can create a tuple in Python by using round brackets:

my_tuple = ()

To add items to your tuple, you need to separate them using commas.

my_list = ('hi', 'world', 1, 2, 3)

Lastly, you can also construct a tuple using the tuple() constructor and optionally passing an iterable to it.

my_tuple = tuple('hello')

Create Tuple

 

Retrieve Elements

You can access elements in a list and tuple using indices within squared brackets. Both data types make use of zero-based indexing, which means that the first item starts at index 0.

It is worth pointing out that accessing elements using tuples is faster than accessing through lists.

Retrieve Elements from List

There are several methods to retrieve elements from a list. Consider the following example:

my_list = [22, 34, 56, 78, 90]

To retrieve the third element, we can pass its corresponding index using a square bracket. The third element is at index 2.

my_list[2]

Retrieve element from list

You can also retrieve an element in the reverse order by passing a negative index. For instance, passing -1 retrieves the last element of the list. Passing -2 retrieves the second last, and so on.

my_list[-1]

Retrieve element from list

If you want to retrieve multiple elements in chronological order, you can use the slice operation and pass the range of indices of the corresponding elements.

The first number is inclusive, whereas the second number is exclusive of the range.

Here, we can retrieve the first 2 elements by passing the range of [0:2].

my_list[0: 2]

Retrieve element from list

The below syntax is useful for reversing the elements of a list. Besides passing a range of indices, we can pass -1 as the last argument inside the square bracket. This reverses the order of the list.

my_list[::-1]

Retrieve element from list

Retrieve Elements from Tuple

Retrieving an element from a tuple involves exactly the same syntax as a list.

my_tuple = (22, 34, 56, 78, 90)

The list reversal feature also works with tuples. We can reverse all elements by specifying the range inside the square brackets.

my_tuple[::-1]

Retrieve element from tuple

 

Update and Delete Elements

As lists are mutable, we can perform the update and delete operations on these. This is not the case for immutable data types, such as tuples. However, a tuple can store mutable objects inside it, such as a list.

Update Elements of List

You can update an element in a list by indexing the element and assigning a new value.

my_list = [22, 34, 56, 78, 90]

my_list[2] = 4

my_list

Update element in list

You can also perform an update in a 2-dimensional or multidimensional list.

my_list =[[22, 34, 56, 78, 90], ['apples', 'bananas', 'oranges']]

To update bananas to mangos, we need to index through the hierarchy of lists. We first index the second list, and then the second item of the second list.

my_list[1][1] = 'mangos'

my_list

Update element in 2d list

We can also insert an element using the insert() function. It takes 2 arguments: the index, and the new value.

my_list = [22, 34, 56, 78, 90]

my_list.insert(3, 50)

Insert element in list

Delete Elements of List

You can use the remove() function to delete an element from a list. It takes as an argument the value that you want to remove. When there are multiple elements with the same value, it removes the first element that matches the value.

my_list = ['apples', 'bananas', 'oranges']

my_list.remove(‘oranges’)

Delete element in list

If you want to delete multiple elements from a list, you can use the del keyword and slice the array.

my_list = [22, 34, 56, 78, 90]

del my_list[1:3]

Delete element in list

 

Merge and Group

Apart from updating the value of an element inside a list, we can add new values to an existing list, or merge two or more lists. Several functions support this.

Tuples do not support append or extend functionality. However, you can merge two or more tuples by declaring a new variable.

Generally, a tuple is used when we want to group any number of items into a single value.

list.append

The list.append() function adds an item to the end of a list.

my_list = [22, 34, 56, 78, 90]

my_list.append(100)

my_list = ['apples', 'bananas', 'oranges']

my_list.append('cherries')

my_list

Append element in list

Using this function, you can also merge two lists by appending the second list at the end of the first one.

my_list = ['apples', 'bananas', 'oranges']

my_list.append([22, 34, 56, 78, 90])

my_list    

Append element in list

list.extend

The extend function is similar to the append function. It adds an element or a list of elements to the end of a list. The difference between the two is that extend treats the argument as iterable.

This means that it iterates through each index of the argument and appends it element by element.

Let’s perform the same task of adding cherries to our list, this time using extend().

my_list = [‘apples’, ‘bananas’, ‘oranges’]

my_list.extend([22, 34, 56, 78, 90])

my_list

Extend element in list

Using + Operator on Lists

Another way to concatenate many lists together is to add them using the + operator.

my_list1 = [1,2,3]

my_list2 = [4,5,6]

my_list3 = my_list1 + my_list2

print (my_list3)

Concatenate element in list

Using + Operator on Tuples

There is a way to merge two or more tuples, but you will need to initialize a new tuple data type to store the result.

my_tuple1 = (1,2,3)

my_tuple2 = (4,5,6)

my_tuple3 = my_tuple1 + my_tuple2

Concatenate element in tuple

 

Check if it’s a List or a Tuple

You can check the data type of a variable using the type() function or the isinstance() function.

Using type()

This function takes as an argument the variable that you need to check and returns the data type of that variable.

my_list = [1,2,3]

type(my_list)

my_tuple = (1,2,3)

type(my_tuple)

Check type of list and tuple

Using isinstance()

This function takes 2 arguments: the variable to check and the class to compare with. It returns true if the data type matches that of the class, and false otherwise.

my_list = [1,2,3]

isinstance(my_list, list)

my_tuple = (1,2,3)

isinstance(my_tuple, tuple)

Check type of list and tuple

Convert a List to Tuple or Tuple to a List

Using type casting, we can convert a list into a tuple and vice versa.

Let’s start by creating a list and converting it into a tuple.

my_list = [1,2,3]

my_list = tuple(my_list)

type(my_list)

Convert list to tuple

We can also convert a tuple into a list by type casting. This returns a new list containing all the items of the given tuple.

my_tuple = (1,2,3)

list(my_tuple)

type(my_tuple)

Convert tuple to list

 

Search a List of Tuples

Using Python’s list comprehension, you can search for a list of tuples with the help of enumerate() function. Searching returns the indices of the tuples that meet your condition.

The enumerate function iterates through each item while keeping a record of its index. You can specify your condition to filter out the values that you want.

Let’s see this with an example.

list_tuples = [('A', 10), ('B', 20), ('B', 30)]

my_tuples = [item for (i, item) in enumerate(list_tuples) if item[0] == 'B']

print(my_tuples)

Search a List of Tuples

 

Similarities and Differences between Lists and Tuples

Both sequence types, lists, and tuples contain a lot of similarities. However, they practically serve very different use cases and can not be substituted for one another.

Although many operations on lists and tuples are similar, the latter offers some additional functionalities that are not available in tuples.

Similarities

Operations

Both, tuples and lists, allow you to index, slice, or concatenate items. However, many operations are exclusive to lists and are not possible to achieve with tuples due to their immutability feature.

This is essentially what differentiates their usage. If you do not want your data to be modified, a tuple will guard against any modification.

If you want to perform various operations on your data, such as inserting or removing elements, lists will be your preferred data type.

We can modify elements in a list.

my_list = ['apples', 'bananas', 'oranges','grapes']

print(my_list)

my_list[0:2] = [1, 3]

print(my_list)

Operations in tuples and lists

Modifying an element in a tuple will thorw an error.

my_tuple = ('apples', 'bananas', 'oranges','grapes')

print(my_tuple)

my_tuple[0:2] = (1, 3)

Operations in tuples and lists

Ordering

Both lists and tuples have an ordered sequence of items. Their order is maintained as you insert values into them. They’re not sorted in an increasing or decreasing order, as one may think.

Rather, the order is defined as how you insert the values in them.

my_list = ['apples', 'bananas', 'oranges']

my_list.append('peaches')

my_list.append('apricot')

my_list

my_tuple = (5,4,6,1,2,3,4)

my_tuple

Ordering in tuples and lists

Element types

Lists and tuples belong to sequence data types in Python. They contain an ordered sequence of objects. These are different from numeric data types because they can store heterogeneous data types.

You can store integers, strings, floats, or any data type inside lists and tuples.

my_list = ['apples', [6.7, 8.8, 9.0], ('immutable', 'tuple')]

my_list

my_tuple =  ['oranges', [6.7, 8.8, 9.0], ('immutable', 'tuple')]

my_tuple

Element types in tuples and lists

Nesting

Lists can store inside them sublists, which in turn can store sublists, up to an arbitrary depth. Likewise, tuples can store inside them sub-tuples to an arbitrary depth. Moreover, lists can hold tuples and tuples can hold lists.

my_list = [[1,2,3,4, [10,20,30,40,[100, 200, 300, 400]]]]

my_list

my_tuple = ((1,2,3,4, (10,20,30,40,(100, 200, 300, 400))))

my_typle

Nesting in tuples and lists

 

Differences

Duplicity

You can create a copy of a list that references to a new variable, but tuples do not allow you to do so. If you assign an existing tuple to a new variable, it will reference the original variable. A copy is not treated in memory.

If we create a new list from a given list, a new copy is created.

my_list = ['apples', 'bananas', 'oranges']

copy_of_list = list(my_list)

print(my_list is copy_of_list)

Duplicity in tuples and lists

Tuples do not follow the same behavior. The new variable references to the original tuple, rather than creating a copy.

my_tuple = ('apples', 'bananas', 'oranges')

copy_of_tuple = tuple(my_tuple)

print(my_tuple is copy_of_tuple)

Duplicity in tuples and lists

Capacity

When you create a tuple in Python, it gets allocated a large block of memory. This creates lower overhead since they are immutable. Lists, on the other hand, are allocated small blocks of memory.

When the number of elements grows inside a list, the processing gets slower since the memory capacity increases.

my_list = ['apples', 'bananas', 'oranges']

my_tuple = ('apples', 'bananas', 'oranges')

print(my_list.__sizeof__())

print(my_tuple.__sizeof__())

my_list.append('mangos')

print(my_list.__sizeof__())

Capacity in tuples and lists

Mutability

You can create a new element or remove existing elements from a list. Tuples do not allow any modification. If you assign a tuple to a new variable, it will reference the original variable.

A copy is not treated. The same is true for lists. However, there are ways to create a copy of a list and perform modifications.

my_list = ['apples', 'bananas', 'oranges']

my_list[0] = 'mangos'
   
my_tuple = ['apples', 'bananas', 'oranges']

my_tuple[0] = 'mangos'

Mutability in tuples and lists

Dynamicity

Tuples are fixed-length data structures. When you create a tuple, you can not change its size. This is not the case for dynamic lists. They can have variable lengths. You can add as many items to a list, and its size will grow as needed.

my_list = ['apples', 'bananas', 'oranges']

print(my_list.__sizeof__())

my_list.append('peaches')

my_list.append('apricot')

print(my_list.__sizeof__())

Dynamicity in tuples and lists

Hashing

Immutable data types, such as tuples, can not be altered. They contain unique values that never change, so they are hashable.

Under the hood, Python hashes immutable objects so that it can store, look up, and retrieve them efficiently. On the other hand, mutable data types can be modified in place.

Lists are examples of mutable data types. Hence, Python does not hash objects of lists.

my_list = ['apples', 'bananas', 'oranges']

print(my_list.__hash__)

my_tuple = ('apples', 'bananas', 'oranges')

print(my_tuple.__hash__)

Hashing in tuples and lists

Memory Consumption

The memory management in lists and tuples is different. Lists behave like dynamic arrays. When new elements are added to a list, their size updates dynamically, and more memory blocks are allocated to that list.

To avoid repetitive callbacks, memory updation does not occur at every insertion of an element. Rather, it happens periodically. Tuples do not require more memory blocks after their initial declaration.

This prevents the allocation of unnecessary memory blocks.

my_list = ['apples', 'bananas', 'oranges']

my_tuple = ('apples', 'bananas', 'oranges')

print(my_list.__sizeof__())

print(my_tuple.__sizeof__())

my_list.append('mangos')

print(my_list.__sizeof__())

Memeory Consumption in tuples and lists

 

Why is Tuple Faster?

When you create a new tuple, references to its elements are directly incorporated. Lists usually have an additional layer of indirection to several pointers.

Moreover, tuples are stored in a single memory block and are hashed for efficient lookups. They do not over-allocate memory blocks, hence are faster to retrieve.

 

When to Use Which?

Although both, tuples and lists, belong to the sequential data types, they have different use cases. When you are working with data that should not be modified, tuples should be your choice.

If you need to perform updating, deletion, and various operations on your data, lists are best suited for your need.


Viewing all articles
Browse latest Browse all 104

Trending Articles