Python: Common data structures

This documentation is part of the Learning Python guide. View the full guide here: A comprehensive Python guide.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Python cloud solution that provides a host of benefits, including:

  • Deploy your application in seconds with a simple git push.
  • Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
  • Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
  • Get optimal performance and robust security thanks to a private and dedicated VM.

Save time and simplify your life: it only takes 5 minutes to try Stackhero's Python cloud hosting solution!

Python provides several data structures to help you efficiently organise, store, and manipulate data. The most commonly used ones are lists, tuples, dictionaries, and sets. Lists and tuples maintain an ordered sequence of elements, dictionaries store key-value pairs, and sets store unique elements. Each structure comes with a range of methods tailored to specific use cases.

  • List: my_list = [1, 2, 3, 4]
  • Tuple: my_tuple = (1, 2, 3, 4)
  • Dictionary: my_dictionary = {'key1': 'value1', 'key2': 'value2'}
  • Set: my_set = {1, 2, 3, 4}

Lists are mutable, ordered collections of elements. They allow duplicates and can contain elements of various data types, including other lists, tuples, dictionaries, or sets. You can easily add, update, and remove elements. Lists are defined within square brackets [] with elements separated by commas.

Key points about lists:

  1. Mutable and ordered
  2. Allow duplicate elements
  3. Maintain the order in which elements are added
  4. Support multiple data types
  5. Provide operations for adding, updating, and deleting elements

Lists are commonly used when you need a dynamic and resizable collection of items.

Examples:

# Create a list
my_list = [1, 2, 3, 4, 5]

# Access elements
print(my_list[0])  # Output: 1
print(my_list[-1])  # Output: 5

# Add elements
my_list.append(6)
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]

# Update elements
my_list[0] = 0
print(my_list)  # Output: [0, 2, 3, 4, 5, 6]

# Delete elements
del my_list[0]
print(my_list)  # Output: [2, 3, 4, 5, 6]

Dictionaries are mutable, unordered collections of key-value pairs. Each key must be unique, and you can use these keys to access their associated values. Like lists, dictionaries can store elements of various data types, including nested collections. They are defined within curly braces {} with key-value pairs separated by commas, and keys and values separated by a colon.

Key points about dictionaries:

  1. Mutable and unordered collection
  2. Consist of key-value pairs with unique keys
  3. Access values using keys
  4. Store various data types

Dictionaries are ideal for tasks where you need to perform lookups, such as configuration settings or frequency counts.

Examples:

# Create a dictionary
my_dictionary = {'a': 1, 'b': 2, 'c': 3}

# Access elements
print(my_dictionary['a'])  # Output: 1

# Add elements
my_dictionary['d'] = 4
print(my_dictionary)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

# Update elements
my_dictionary['a'] = 0
print(my_dictionary)  # Output: {'a': 0, 'b': 2, 'c': 3, 'd': 4}

# Delete elements
del my_dictionary['a']
print(my_dictionary)  # Output: {'b': 2, 'c': 3, 'd': 4}

Tuples are immutable, ordered collections of elements. They work much like lists, except that once a tuple is created, its elements cannot be changed, added, or removed. Tuples are defined using parentheses () with elements separated by commas.

Key points about tuples:

  1. Immutable and ordered collection
  2. Support multiple data types
  3. Fixed-size structure

Tuples are useful when you need an unchangeable collection, or when you want to use the collection as a dictionary key.

Example:

# Create a tuple
my_tuple = (1, 2, 3, 4, 5)

# Access elements
print(my_tuple[0])  # Output: 1
print(my_tuple[-1])  # Output: 5

# Note: Tuples are immutable

Sets are mutable, unordered collections that store unique elements. They automatically remove duplicates and do not maintain an order. Sets can hold elements of various data types, excluding mutable types like lists and dictionaries. They can be defined using curly braces {} or the set() constructor.

Key points about sets:

  1. Mutable and unordered
  2. Store only unique elements, automatically removing duplicates
  3. Exclude mutable types (like lists and dictionaries)

Sets are ideal for membership testing, deduplication, and performing set operations like union, intersection, and difference.

# Create a set
my_set = {1, 2, 3, 4, 5}

# Check membership
print(1 in my_set)  # Output: True

# Add an element
my_set.add(6)
print(my_set)  # Output: {1, 2, 3, 4, 5, 6}

# Update by removing one element and adding another
my_set.remove(1)
my_set.add(0)
print(my_set)  # Output: {0, 2, 3, 4, 5, 6}

# Delete an element
my_set.remove(0)
print(my_set)  # Output: {2, 3, 4, 5, 6}