Introduction
Python offers several built-in data types that help store collections of data. Among the most commonly used are Lists, Tuples, Sets, and Dictionaries. Understanding these data types is fundamental to writing efficient and organized code. This article provides an overview of these four data types, explaining their characteristics and use cases.
Objective
The objective of this topic is to explain the concept of Python data types: Lists, Tuples, Sets, and Dictionaries. You will learn how to create and manipulate these data types, which will enhance your ability to write clean, effective Python programs.
Python Code Example
# Python Data Types: Lists, Tuples, Sets, and Dictionaries
# Lists: Ordered and mutable collection
my_list = [1, 2, 3, 4, 5]
print("List:", my_list)
# Tuples: Ordered but immutable collection
my_tuple = (1, 2, 3, 4, 5)
print("Tuple:", my_tuple)
# Sets: Unordered collection of unique elements
my_set = {1, 2, 3, 4, 5}
print("Set:", my_set)
# Dictionaries: Unordered collection of key-value pairs
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
print("Dictionary:", my_dict)
# Adding elements to the List and Dictionary
my_list.append(6) # List is mutable
my_dict["date"] = 4 # Dictionary is mutable
print("Updated List:", my_list)
print("Updated Dictionary:", my_dict)
Explanation of the Program
The above Python code demonstrates the use of four different data types: Lists, Tuples, Sets, and Dictionaries. Below is an explanation of each section of the program:
- List: A List is an ordered, mutable collection that allows duplicates. In the code, we define a List
my_list
and add a new element to it usingappend()
. - Tuple: A Tuple is similar to a List but is immutable, meaning once created, you cannot modify its elements. The code creates a Tuple
my_tuple
and prints it without modifying it. - Set: A Set is an unordered collection of unique elements. In the code,
my_set
is a Set, and even if duplicates are added, they will be ignored. - Dictionary: A Dictionary stores key-value pairs. The code shows how to create a Dictionary
my_dict
and add a new key-value pair to it.
How to Run the Program
To run this program, you need to have Python installed on your system. Here are the steps to execute the code:
- Install Python from the official website: Python Downloads.
- Save the code into a file with a .py extension (e.g.,
data_types.py
). - Open a terminal or command prompt and navigate to the folder where the file is saved.
- Run the program by typing
python data_types.py
in the terminal and pressing Enter. - The program will output the List, Tuple, Set, and Dictionary along with their updated values.