12
Chapter – 2
PYTHON DATA ARRANGEMENT FORMATS
2.1 Lists and Tuples
Lists and tuples in Python are both used to store collections of items, but they serve slightly
different purposes due to their inherent properties. Lists, which are enclosed in square
brackets, are mutable, meaning that the contents can be changed after they are created. This
flexibility allows for modifications such as adding, removing, or altering elements within
the list. This makes lists particularly useful for scenarios where the data set needs to be
dynamic or updated frequently. For example, lists are often used to store sequences of data
that will change, such as user inputs, configurations that may need to be adjusted, or data
that evolves over the course of a program's execution. The ability to change the list makes it
versatile for a wide range of applications, from simple data aggregation to complex data
manipulation tasks in various domains, including web development, data analysis, and
machine learning.
On the other hand, tuples are enclosed in parentheses and are immutable, meaning once they
are created, their contents cannot be altered. This immutability provides a form of integrity
and security, ensuring that the data cannot be changed accidentally or intentionally, which
can be crucial for maintaining consistent data states. Tuples are often used to represent fixed
collections of items, such as coordinates, RGB colour values, or any data set that should
remain constant throughout the program. The immutability of tuples can lead to more
predictable and bug-free code, as developers can be certain that the data will not be altered.
Additionally, because they are immutable, tuples can be used as keys in dictionaries, which
require immutable types. This makes tuples suitable for scenarios where constant and
unchanging data is necessary, enhancing both the readability and reliability of the code.
2.1.1 Creating Lists and Tuples
Creating a List: A list is created by placing all the items (elements) inside
square brackets [], separated by commas.
my_list = [1, 2, 3, 4, 5]
Creating a Tuple: A tuple is created by placing all the items (elements)
inside parentheses (), separated by commas.
my_tuple = (1, 2, 3, 4, 5)