Table of Contents

Data Structures (Lists, Tuples, Sets, Dictionaries, Sequences and Comprehensions) in Python

Table of Contents

Python provides a number of built-in data structures that allow you to store and manipulate data in different ways. Here are some of the most commonly used data structures in Python, along with their functions:

  1. Lists: Lists are ordered sequences of elements. They can contain any type of data, including other lists. Some of the most commonly used functions for lists are:

    • append: adds an element to the end of the list
    • insert: inserts an element at a specific index
    • remove: removes the first occurrence of a value from the list
    • pop: removes and returns the element at a specific index
    • index: returns the index of the first occurrence of a value
    • sort: sorts the elements of the list in ascending order
    • reverse: reverses the order of the elements in the list
    # create a list of integers
    my_list = [1, 2, 3, 4, 5]
    
    # print the entire list
    print(my_list)
    
    # print the first element of the list
    print(my_list[0])
    
    # print the last element of the list
    print(my_list[-1])
    
    # change the value of an element in the list
    my_list[2] = 10
    
    # add an element to the end of the list
    my_list.append(6)
    
    # insert an element at a specific position
    my_list.insert(2, 8)
    
    # remove an element from the list
    my_list.remove(4)
    
    # get the length of the list
    print(len(my_list))
    
    # sort the list in ascending order
    my_list.sort()
    
    # reverse the order of the list
    my_list.reverse()
    
    # print the list using a for loop
    for element in my_list:
        print(element)
  2. Tuples: Tuples are ordered, immutable sequences of elements. They are similar to lists, but once a tuple is created, its elements cannot be changed. Some of the commonly used functions for tuples are:

    • count: returns the number of occurrences of a value in the tuple
    • index: returns the index of the first occurrence of a value in the tuple
    # create a tuple of integers
    my_tuple = (1, 2, 3, 4, 5)
    
    # print the entire tuple
    print(my_tuple)
    
    # print the first element of the tuple
    print(my_tuple[0])
    
    # print the last element of the tuple
    print(my_tuple[-1])
    
    # get the length of the tuple
    print(len(my_tuple))
    
    # convert the tuple to a list
    my_list = list(my_tuple)
    
    # add an element to the list
    my_list.append(6)
    
    # convert the list back to a tuple
    my_tuple = tuple(my_list)
    
    # print the tuple using a for loop
    for element in my_tuple:
        print(element)
  3. Dictionaries: Dictionaries are unordered collections of key-value pairs. They are used to store and retrieve data based on a unique key. Some of the commonly used functions for dictionaries are:

    • keys: returns a list of all the keys in the dictionary
    • values: returns a list of all the values in the dictionary
    • items: returns a list of all the key-value pairs in the dictionary
    • get: returns the value associated with a specific key, or a default value if the key is not found
    • pop: removes and returns the value associated with a specific key
    # create a dictionary of key-value pairs
    my_dict = {'apple': 2.99, 'banana': 0.99, 'orange': 1.49}
    
    # print the entire dictionary
    print(my_dict)
    
    # print the value associated with a specific key
    print(my_dict['apple'])
    
    # add a new key-value pair to the dictionary
    my_dict['pear'] = 1.99
    
    # remove a key-value pair from the dictionary
    del my_dict['banana']
    
    # get the number of key-value pairs in the dictionary
    print(len(my_dict))
    
    # print the keys in the dictionary using a for loop
    for key in my_dict.keys():
        print(key)
    
    # print the values in the dictionary using a for loop
    for value in my_dict.values():
        print(value)
    
    # print the key-value pairs in the dictionary using a for loop
    for key, value in my_dict.items():
        print(key, value)
  4. Sets: Sets are unordered collections of unique elements. They can be used for operations like union, intersection, and difference. Some of the commonly used functions for sets are:

    • add: adds an element to the set
    • remove: removes an element from the set
    • union: returns a new set with all the elements from both sets
    • intersection: returns a new set with the elements that are common to both sets
    • difference: returns a new set with the elements that are in the first set but not in the second set
    # create a set of integers
    my_set = {1, 2, 3, 4, 5}
    
    # print the entire set
    print(my_set)
    
    # add an element to the set
    my_set.add(6)
    
    # remove an element from the set
    my_set.remove(2)
    
    # check if an element is in the set
    print(3 in my_set)
    
    # get the number of elements in the set
    print(len(my_set))
    
    # print the set using a for loop
    for element in my_set:
        print(element)

These are just a few of the many data structures and functions available in Python. By using these data structures and their functions, you can perform a wide variety of operations on your data, from simple list manipulations to complex dictionary lookups and set operations.


Comprehensions in Python

In Python, comprehensions are a concise way to create sequences, such as lists, dictionaries, and sets, from other sequences, with an optional filtering or mapping step. Comprehensions are often used to simplify code and make it more readable.

There are three types of comprehensions in Python:

  1. List comprehensions: List comprehensions are used to create lists from other sequences, such as lists or ranges. They have the following syntax:

    [expression for variable in sequence if condition]

    Here, expression is the value you want to generate, variable is the variable that will take on each value in sequence, and condition is an optional expression that filters the values. For example, you can use a list comprehension to generate a list of even numbers from 0 to 9:

    even_numbers = [i for i in range(10) if i % 2 == 0]
  2. Dictionary comprehensions:Dictionary comprehensions are used to create dictionaries from other sequences, such as lists or ranges. They have the following syntax:

    {key_expression: value_expression for variable in sequence if condition}

    Here, key_expression is the expression that generates the keys, value_expression is the expression that generates the values, variable is the variable that will take on each value in sequence, and condition is an optional expression that filters the values. For example, you can use a dictionary comprehension to create a dictionary of the squares of the first 5 positive integers:

    squares = {i: i**2 for i in range(1, 6)}
  3. Set comprehensions:Set comprehensions are used to create sets from other sequences, such as lists or ranges. They have the following syntax:

    {expression for variable in sequence if condition}

    Here, expression is the value you want to generate, variable is the variable that will take on each value in sequence, and condition is an optional expression that filters the values. For example, you can use a set comprehension to generate a set of the unique letters in a string:

    unique_letters = {char for char in 'hello world' if char.isalpha()}

Comprehensions are a powerful feature of Python that allow you to create sequences quickly and easily, with less code than traditional loops and conditionals. By using comprehensions, you can write more concise and readable code that is easier to understand and maintain.


Sequences

In Python, a sequence is a type of data structure that holds an ordered collection of elements, with each element identified by an index. There are three main types of sequences in Python:

  1. Lists: A list is a collection of elements that are ordered and changeable. Lists are denoted by square brackets [ ] and can contain elements of different data types. For example:
    my_list = [1, 2, 3, 'hello', 'world']
  2. Tuples: A tuple is a collection of elements that are ordered and unchangeable. Tuples are denoted by parentheses ( ) and can also contain elements of different data types. For example:
    my_tuple = (1, 2, 3, 'hello', 'world')
  3. Strings: A string is a sequence of characters that are ordered and unchangeable. Strings are denoted by quotes, either single quotes ‘ ‘ or double quotes ” “. For example:
    my_string = "hello world"

All three types of sequences support indexing, slicing, and several other common operations, such as concatenation and repetition.

In addition to these basic sequence types, Python also has several built-in sequence functions and methods that can be used to manipulate sequences. Some of these include len() to get the length of a sequence, sorted() to sort a sequence, and append() to add an element to a list.

Overall, sequences are an important part of Python and are used extensively in many types of programs, from simple scripts to complex applications.


Slicing in Python

Slicing is a powerful feature in Python that allows you to extract a portion of a sequence (such as a string, list, or tuple) by specifying a range of indices. The basic syntax for slicing is sequence[start:stop:step], where start is the index of the first element to include, stop is the index of the first element to exclude, and step is the size of the step between elements. Here’s an example of how to use slicing with a list in Python:

# create a list of integers
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# print the entire list
print(my_list)

# slice the list to get the first three elements
print(my_list[:3])

# slice the list to get the last three elements
print(my_list[-3:])

# slice the list to get every other element
print(my_list[::2])

# slice the list to get every third element, starting from the second element
print(my_list[1::3])

In this example, we create a list of integers and use slicing to extract various subsets of the list. We use my_list[:3] to get the first three elements of the list, my_list[-3:] to get the last three elements of the list, my_list[::2] to get every other element of the list, and my_list[1::3] to get every third element of the list starting from the second element. Slicing is a very useful feature in Python, and can help you work more efficiently with sequences of data.

Category
Tags

Copyright 2023-24 © Open Code