×

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data types that are used to store a collection of values. The other two built-in types are set and dictionary. These are sequential data types, meaning you can iterate over the elements stored in them. It is so important to be able to differentiate between these data types.

Python List

Lists are one of the built-in data types in Python. Lists are primarily used to store multiple values of the same or different data types in a single variable. In other words, Lists are used for storing a collection of data.

Lists don’t have to be homogenous, so they can store different types of values, which is a very powerful feature in a programming language. Lists are dynamically sized arrays, so we can increase or decrease their size per our requirement.

Lists are created using a square bracket [ ], and the data Inside it is separated using a comma (,).

Syntax:

# creating list
list_name = [data1, data2, data3,…..]

Example:

#  creating a list of integer
Student_age = [ 15, 20, 30, 40 ]


# creating a list of mixed data types like integer, float and string
my_var = [ 1,  ‘TutorialAndExample’ , 5.6 ]

Explanation:

In the above example, we have created a list with the variable name Student_age and assigned it values which are of the same data type integer. Also, we have created a list of mixed data types with the variable name my_var and assigned it an integer value, a string value and a string value.

Accessing Elements in a List:

We use the index operator [ ] to access elements of a list. To access the first element of a list, we will access it using index 0.

Let’s understand with an example.

# creating lists
list_name = [ 1, 2.5, ‘ Hi! ’ ]


#accessing the elements of lists
print( list_name[0] )     #  This line will print 1
print( list_name[1] )     # This line will print 2.5
print( list_name[2] )     # This line will print Hi!

Explanation:

In the above example, we have created a list of name list_name and stored values of mixed data type. After that, we accessed those data types using the output function print and the access operator ( [ ] ).

Python Tuples

Python tuples are also used for storing multiple values of one or more than one data type in a single variable. Tuples are used to store a collection of ordered data which can’t be changed. Tuples don’t have to be homogenous, same as a list. Tuples allow duplicate values (more than one similar data) to store in them.

Tuples are created using parenthesis (), and elements are separated using comma (,). However, parentheses are optional in the case of tuples. We can create tuples with or without a pair of parentheses. Creating tuples without parentheses is known as tuple packing.

Syntax:

# creating tuples using parentheses
tuple_name = (‘data1’, ‘data2’, ‘data3’, ‘data4’)


# creating tuples without using parentheses
# tuple packing 
tuple_name = data1 , data2, data3

Example:

# Different types of tuple


# empty tuple
first_tuple = ( )
print (first_tuple)


# tuple of integers
first_tuple = ( 1,2,3,4 )
print (first_tuple)


# tuple with mixed data types
first_tuple = ( 1, ‘A’, 2.5)
print (first_tuple)


# nested tuple
first_tuple = (“TutorialAndExample”, [ 9,10,11 ] , (1,2,3) )
print(first_tuple)


Outputs:

( )
( 1, 2, 3, 4 )
( 1, ‘A’, 2.5 )
(‘TutorialAndExample’, [ 9, 10, 11 ], ( 1, 2,3 ))

Explanation:

The above code shows the different ways to create a tuple and print its value.

Difference between List and Tuple

Syntax Difference

The syntax for creating a list and a tuple are different. Lists are created using square brackets. While on the other hand, tuples are created using parentheses which is optional. For example,

creating_list  =  [‘a’, ‘b’, ‘c’, ‘d’]
                 creating_tuple  =  ( ‘a’, ‘b’, ‘c’, ‘d’ )

Mutable Lists and Immutable Tuples

The most important difference between a list and a tuple is that lists are mutable, which means they can be changed or manipulated. In contrast, tuples are immutable, which means they can’t be changed or manipulated once they are created.

Iteration

Iterating a list is slower and more time-consuming, whereas iterating a tuple is faster.

Memory Consumption

Lists have more memory consumption compared to tuples. Since lists are mutable, they consume more memory space. Tuples operation has a smaller size than that of lists.

Usefulness

Lists are very useful for insertion and deletion operations, whereas tuples are very useful for read-only operations.

Methods

Lists provide more built-in functions as compared to tuples. To get all the associated built-in functions related to lists and tuples, we use the dir([objects])  command.

Security

List elements are more prone to getting errors while tuples operations are safer.


Related Topics

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Python Set symmetric_difference() method

Python Set symmetric_difference() method The set.symmetric_difference() method returns a new set, which is the symmetric difference of two sets. The returned set contains only the unique items and, hence, deleting the common elements of...

2 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

Loan Calculator using PyQt5 in Python

In the following tutorial, we will learn how to build a Loan Calculator application using the PyQt5 library in the Python programming language. So, let's get started. Introduction to the code: The heading...

4 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

os.rename() method in Python

In Python, the os module provides the capacity to interact with the operating system. The operating system comes under the Python module. In this module, Python provides a specific feature...

3 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

Python MySQL Update Operation

Python MySQL Update Operation: In this part of tutorial, we will learn that how can we update a table present in SQL database through our Python program. As like SQL,...

4 minutes read.

Python - Binomial Distribution

Introduction Definition of the Binomial Distribution The method of counting how many instances of a specific event there have been is called the binomial distribution. It will outline the possible outcomes or...

4 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.

Palindrome program in Python

Palindrome program in python A number or string is said to be a palindrome if we invert the number or string and the string or number remains the same as the...

3 minutes read.

Python memoryview() Function

Python memoryview() Function The memoryview() function in Python returns a memory view object from a specified object. Syntax memoryview(obj) Parameter obj: This parameter represents a Bytes object or a bytearray object. Return This function returns a “memory view” object...

1 minute read.

any() Keyword in python

“any” keyword in python This page contains all the information about any () Keyword in python, how it is used with lists, tuples, dictionaries, sets, and what its function is? Python...

3 minutes read.

Python callable() Function

Python callable() Function The callable() function returns a boolean value ‘True’ if the specified object is callable, else it returns False. Syntax callable(object) Parameter Object:  The object parameter represents the value to test if it is callable...

1 minute read.

Python Functionalities of Pillow Module

This instructional exercise is about "Pillow" library, one of the significant libraries of python for picture control. Pillow library of python, is an easy to use and also open source...

14 minutes read.