General-purpose programming language.
Python data structures are a fundamental aspect of the language that every programmer should be familiar with. They are containers that hold data and provide various ways to store, access, and manipulate that data. In this unit, we will explore the four primary data structures in Python: Lists, Tuples, Sets, and Dictionaries.
A list in Python is an ordered collection of items. Lists are mutable, meaning they can be changed after they are created. They are defined by enclosing a comma-separated sequence of items in square brackets []
.
my_list = [1, 2, 3, 'Python', 5.0]
You can access elements in a list by their index, modify elements, and delete elements using the del
statement. Python also supports slicing, which allows you to access a range of items in a list.
A tuple is similar to a list in that it is an ordered collection of items. However, tuples are immutable, meaning they cannot be changed after they are created. Tuples are defined by enclosing a comma-separated sequence of items in parentheses ()
.
my_tuple = (1, 2, 3, 'Python', 5.0)
Like lists, you can access elements in a tuple by their index and use slicing. However, you cannot modify or delete elements in a tuple.
A set in Python is an unordered collection of unique items. Sets are mutable, but they cannot contain mutable items. They are defined by enclosing a comma-separated sequence of items in curly braces {}
.
my_set = {1, 2, 3, 'Python', 5.0}
You can add and remove elements in a set using the add
and remove
methods, respectively. Python also provides methods to perform standard set operations, such as union, intersection, and difference.
A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are mutable, and each key-value pair is separated by a colon :
. They are defined by enclosing a comma-separated sequence of key-value pairs in curly braces {}
.
my_dict = {'name': 'Python', 'version': 3.9, 'type': 'programming language'}
You can access, modify, and delete elements in a dictionary using their keys. Python also provides methods to get a list of keys, values, or key-value pairs.
In conclusion, understanding Python data structures and their properties is crucial for effective programming. They provide a way to organize and manipulate data, which is essential in tasks ranging from simple calculations to complex data analysis and machine learning.