Python Built-In Data Structures and their Methods and Functions.

Faheem Khan
10 min readFeb 27, 2023

--

Built-in python data structures and their useful methods and functions for daily use in Python programmers, listed Chronologically to start learning Python for Data Science.

Source Medium

Python provides several built-in data structures, including:

  1. Lists: A collection of ordered and mutable elements. Lists are defined using square brackets [] and can hold elements of different types.
  2. Tuples: A collection of ordered and immutable elements. Tuples are defined using parentheses () and can hold elements of different types.
  3. Sets: An unordered collection of unique elements. Sets are defined using curly braces {} or the set() function.
  4. Dictionaries: A collection of key-value pairs. Dictionaries are defined using curly braces {} and colons : to separate keys and values.
  5. Strings: A sequence of characters. Strings are defined using single quotes ‘ ‘ or double quotes “ “ and are immutable.
  6. Range: A sequence of numbers. Ranges are defined using the range() function and are typically used for looping over a sequence of numbers.

Each of these data structures has its own unique features and use cases.

Use Cases :

There are specific conditions that can influence the choice of data structure for a specific task. Here are some guidelines to consider when choosing a data structure:

  1. Lists are a good choice when you need to store a collection of ordered and mutable elements, and you need to access them by their index. Lists are also useful when you need to add or remove elements from the collection.
  2. Tuples are a good choice when you need to store a collection of ordered and immutable elements, and you don’t need to modify the collection. Tuples are also useful when you want to use them as keys in a dictionary.
  3. Sets are a good choice when you need to store a collection of unique elements, and you don’t need to access them by their index. Sets are also useful when you need to perform set operations like union, intersection, and difference.
  4. Dictionaries are a good choice when you need to store a collection of key-value pairs and you need to access the values by their keys. Dictionaries are also useful when you need to check if a key exists in the collection.
  5. Strings are a good choice when you need to store a sequence of characters and you don’t need to modify the sequence.
  6. Range is a good choice when you need to generate a sequence of numbers that you want to loop over.

In general, the choice of data structure depends on the specific requirements of your task. You should choose the data structure that best fits your needs in terms of performance, memory usage, and functionality.

1. Lists [ ]

Here are some of the common methods and functions that can be used with lists in Python:

Creating a list:

  • [] or list(): creates an empty list
  • [element1, element2, ..., elementN]: creates a list with N elements
  • list(iterable): creates a list from an iterable (e.g. a tuple or string)

Accessing elements:

  • list[index]: returns the element at the specified index. Raises an IndexError if the index is out of range.
  • list[start:end:step]: returns a slice of the list from the start index (inclusive) to the end index (exclusive) with the specified step. Negative indices count from the end of the list.

Modifying elements:

  • list[index] = value: sets the element at the specified index to the specified value. Raises an IndexError if the index is out of range.
  • list.append(element): adds the specified element to the end of the list.
  • list.insert(index, element): inserts the specified element at the specified index, shifting existing elements to the right.
  • list.extend(iterable): adds the elements from the specified iterable to the end of the list.

Removing elements:

  • list.pop([index]): removes and returns the element at the specified index. If no index is provided, removes and returns the last element.
  • list.remove(element): removes the first occurrence of the specified element from the list. Raises a ValueError if the element is not found.
  • list.clear(): removes all elements from the list.

List methods:

  • list.sort(key=None, reverse=False): sorts the elements of the list in ascending order. Optional parameters allow for custom sorting functions and reverse sorting.
  • list.reverse(): reverses the order of the elements in the list.
  • list.count(element): returns the number of times the specified element appears in the list.
  • list.index(element): returns the index of the first occurrence of the specified element in the list. Raises a ValueError if the element is not found.

List properties:

  • len(list): returns the number of elements in the list
  • element in list: returns True if the element is in the list, otherwise False

Note that lists can contain elements of any type, including other lists or mutable objects. Because lists are mutable, they can be modified in place using the above methods.

List all methods:

  • append(): Adds an element to the end of the list.
  • extend(): Adds the elements of another list (or any iterable) to the end of the list.
  • insert(): Inserts an element at a specific index in the list.
  • remove(): Removes the first occurrence of a specified element from the list.
  • pop(): Removes and returns the element at a specific index in the list.
  • clear(): Removes all elements from the list.
  • sort(): Sorts the elements of the list in ascending order (or in descending order if the reverse=True argument is passed).
  • reverse(): Reverses the order of the elements in the list.
  • copy() : Return a shallow copy of the list. Equivalent to a[:].
  • count() : Return the number of times x appears in the list.
  • index(x[,start[,end]] : Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

List functions:

  • len(): Returns the number of elements in the list.
  • sum(): Returns the sum of all elements in the list.
  • min(): Returns the smallest element in the list.
  • max(): Returns the largest element in the list.
  • sorted(): Returns a new sorted list with the elements of the original list.
  • reversed(): Returns a new reversed list with the elements of the original list.
# Examples 

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']

fruits.count('apple')
# Output = 2

fruits.count('tangerine')
# Output =0

fruits.index('banana')
# Output =3

fruits.index('banana', 4) # Find next banana starting at position 4
# Output =6

fruits.reverse()
fruits
# Output = ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

fruits.append('grape')
fruits
# Output = ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']

fruits.sort()
fruits
# Output = ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']

fruits.pop()
# Output = 'pear'

Note that this is not an exhaustive list, and there are many more methods and functions that can be used with lists in Python. Additionally, some methods and functions may not be applicable or useful for every use case with lists.

2. Sets ( ) , { }

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the below section.

Here is a brief Demonstration:

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket) # show that duplicates have been removed
# Output = {'orange', 'banana', 'pear', 'apple'}


'orange' in basket # fast membership testing
# Output = True


'crabgrass' in basket
# Output = False

# Demonstrate set operations on unique letters from two words

a = set('abracadabra')
b = set('alacazam')
a # unique letters in a
# Output = {'a', 'r', 'b', 'c', 'd'}


a - b # letters in a but not in b
# Output = {'r', 'd', 'b'}


a | b # letters in a or b or both
# Output = {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}


a & b # letters in both a and b
# Output = {'a', 'c'}


a ^ b # letters in a or b but not both
# Output = {'r', 'd', 'b', 'm', 'z', 'l'}

Creating a set:

  • set(): creates an empty set
  • {}: creates an empty dictionary, not a set. To create a non-empty set, use the set() function or enclose a list of values in curly braces.
  • set(iterable): creates a set from an iterable (e.g. a list or tuple)

Adding and removing elements:

  • set.add(element): adds an element to a set
  • set.update(iterable): adds multiple elements to a set
  • set.remove(element): removes an element from a set. Raises a KeyError if the element is not in the set.
  • set.discard(element): removes an element from a set if it is present, otherwise does nothing.
  • set.pop(): removes and returns an arbitrary element from a set. Raises a KeyError if the set is empty.

Set operations:

  • set.union(other_set): returns a new set that contains all the elements from both sets
  • set.intersection(other_set): returns a new set that contains only the elements that are common to both sets
  • set.difference(other_set): returns a new set that contains only the elements that are in the first set but not in the second set
  • set.symmetric_difference(other_set): returns a new set that contains only the elements that are in one of the sets but not in both
  • set.issubset(other_set): returns True if the first set is a subset of the second set
  • set.issuperset(other_set): returns True if the first set is a superset of the second set
  • set.isdisjoint(other_set): returns True if the two sets have no common elements

Set properties:

  • set.copy(): returns a shallow copy of the set
  • len(set): returns the number of elements in the set
  • element in set: returns True if the element is in the set, otherwise False
  • set.clear(): removes all elements from the set

Note that all of these methods and functions operate on sets in place, except for union, intersection, difference, and symmetric_difference, which return new sets.

3. Tuples ( )

We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.

A tuple consists of a number of values separated by commas, for instance:

t = 12345, 54321, 'hello!'
t[0]
# Output = 12345

t
# Output = (12345, 54321, 'hello!')


# -----Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u
# Output = ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))


# -----Tuples are immutable:
t[0] = 88888
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v
# Output = ([1, 2, 3], [3, 2, 1])

Python tuples are ordered collections of immutable elements. Here are some of the most commonly used methods and functions for working with tuples in Python:

Creating a tuple:

  • () or tuple(): creates an empty tuple
  • (element1, element2, ..., elementN): creates a tuple with N elements
  • tuple(iterable): creates a tuple from an iterable (e.g. a list or string)

Accessing elements:

  • tuple[index]: returns the element at the specified index. Raises an IndexError if the index is out of range.
  • tuple[start:end:step]: returns a slice of the tuple from the start index (inclusive) to the end index (exclusive) with the specified step. Negative indices count from the end of the tuple.

Tuple methods:

  • tuple.count(element): returns the number of times the specified element appears in the tuple
  • tuple.index(element): returns the index of the first occurrence of the specified element in the tuple. Raises a ValueError if the element is not found.

Tuple properties:

  • len(tuple): returns the number of elements in the tuple
  • element in tuple: returns True if the element is in the tuple, otherwise False

Note that because tuples are immutable, they do not have methods for modifying their contents. If you need to change the contents of a tuple, you will need to create a new tuple with the desired elements.

4. Dictonaries { }

In Python, dictionaries are unordered collections of key-value pairs. Here are some of the most commonly used methods and functions for working with dictionaries in Python:

Creating a dictionary:

  • {}: creates an empty dictionary
  • {key1: value1, key2: value2, ..., keyN: valueN}: creates a dictionary with N key-value pairs
  • dict() or dict(iterable): creates a dictionary from an iterable of key-value pairs

Accessing values:

  • dict[key]: returns the value associated with the specified key. Raises a KeyError if the key is not found.
  • dict.get(key, default=None): returns the value associated with the specified key, or the default value if the key is not found.
  • dict.keys(): returns a view object containing the keys of the dictionary.
  • dict.values(): returns a view object containing the values of the dictionary.
  • dict.items(): returns a view object containing the key-value pairs of the dictionary as tuples.

Adding and modifying key-value pairs:

  • dict[key] = value: sets the value associated with the specified key. If the key does not exist in the dictionary, a new key-value pair is created.
  • dict.update(iterable): updates the dictionary with key-value pairs from an iterable.
  • dict.pop(key, default=None): removes the key-value pair with the specified key and returns the value. If the key is not found and default is not provided, raises a KeyError.

Removing key-value pairs:

  • del dict[key]: removes the key-value pair with the specified key. Raises a KeyError if the key is not found.
  • dict.clear(): removes all key-value pairs from the dictionary.

Dictionary properties:

  • len(dict): returns the number of key-value pairs in the dictionary.
  • key in dict: returns True if the key is in the dictionary, otherwise False.

Note that keys in a dictionary must be immutable types (e.g. strings, numbers, or tuples containing only immutable types), while values can be any object. Additionally, the order of the key-value pairs in a dictionary is arbitrary and may change between calls to the same dictionary.

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
tel
# Output = {'jack': 4098, 'sape': 4139, 'guido': 4127}

tel['jack']
# Output = 4098

del tel['sape']
tel['irv'] = 4127
tel
# Output = {'jack': 4098, 'guido': 4127, 'irv': 4127}

list(tel)
# Output = ['jack', 'guido', 'irv']

sorted(tel)
# Output = ['guido', 'irv', 'jack']

'guido' in tel
# Output = True

'jack' not in tel
# Output = False

The dict() constructor builds dictionaries directly from sequences of key-value pairs:

dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
# Output = {'sape': 4139, 'guido': 4127, 'jack': 4098}

In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:

{x: x**2 for x in (2, 4, 6)}
# Output = {2: 4, 4: 16, 6: 36}

When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:

dict(sape=4139, guido=4127, jack=4098)
# Output = {'sape': 4139, 'guido': 4127, 'jack': 4098}

--

--

Faheem Khan
Faheem Khan

Written by Faheem Khan

AI/ML Engineer | Writing on algorithms, data, and AI’s transformative impact. Passionate about simplifying complexity and inspiring innovation. Let’s create!

Responses (2)