Python Data Structures: Lists, Tuples, Dictionaries, and Sets

Python, a versatile and powerful programming language, offers a variety of data structures to store and manipulate data. In this blog, we’ll explore four fundamental Python data structures: lists, tuples, dictionaries, and sets.

Lists

A list in Python is an ordered collection of items that can be of any type. Lists are mutable, meaning you can change their content.

# Creating a list
fruits = ['apple', 'banana', 'cherry']
print(fruits)

# Adding an item to the list
fruits.append('dragonfruit')
print(fruits)

# Removing an item from the list
fruits.remove('banana')
print(fruits)

Tuples

A tuple is similar to a list in that it’s an ordered collection of elements. However, tuples are immutable.

# Creating a tuple
fruits = ('apple', 'banana', 'cherry')
print(fruits)

# Trying to change a tuple (this will cause an error)
fruits[1] = 'dragonfruit'

Dictionaries

A dictionary in Python is an unordered collection of key-value pairs. Dictionaries are mutable, and each key-value pair in a dictionary is separated by a colon :.

# Creating a dictionary
fruit_colors = {
    'apple': 'red',
    'banana': 'yellow',
    'cherry': 'red'
}
print(fruit_colors)

# Adding a key-value pair to the dictionary
fruit_colors['dragonfruit'] = 'pink'
print(fruit_colors)

# Removing a key-value pair from the dictionary
del fruit_colors['banana']
print(fruit_colors)

Sets

A set in Python is an unordered collection of unique elements. Sets are mutable and can be used to perform mathematical set operations like union, intersection, difference, etc.


# Creating a set
fruits = {'apple', 'banana', 'cherry'}
print(fruits)

# Adding an item to the set
fruits.add('dragonfruit')
print(fruits)

# Removing an item from the set
fruits.remove('banana')
print(fruits)

In conclusion, Python’s data structures like lists, tuples, dictionaries, and sets are powerful tools that allow you to store and manipulate data effectively. By understanding these data structures, you can write more efficient and cleaner code.

Python Basics Home Page [TOC]                 Python_Functions and Modules                   Python Mastering File I/O

You may also like...

Leave a Reply