liveBook · Manning

Data structure

As explained in Get Programming: Learn to code with Python

A data structure is an organized representation for storing and accessing information in a particular format.

A data structure is an organized way to store information in a particular format. Choosing one helps a program access, modify, and work with data appropriately. section 1.2 section 29.3

Use data structures to make information easier for a program to handle:

  • Choose among learned data types before coding, and select the simplest suitable option when several could work. section 29.3
  • Put related data into a container when modifying its contents is more useful than creating a replacement container. section 24.0
  • Break a large string into a list when separate elements, such as individual words, are easier to process. section 29.3

Turning document text into a list

A document begins as one large string, but a word-comparison program needs its words separately. Clean newline and punctuation characters, split the remaining text at spaces, and return the resulting list. Testing the function first on a short file makes mistakes easier to find. section 29.3

Listing 29.2. Finding words from a string
import string                                      #1
def find_words(text):
    """
    text: string
    returns: list of words from input text
    """
    text = text.replace("\n", " ")                 #2
    for char in string.punctuation:                #3
        text = text.replace(char, "")              #4

    words = text.split(" ")                        #5
    return words                                   #6

words = find_words(text)                           #7

Inspect the complete find_words function, including cleanup, punctuation removal, splitting, and returning the list. section 29.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Defines the idea, contrasts modifiable containers, and works through converting document text into a list.
Examples
Uses country lists, mutable containers, cleaned text, and a word list extracted from a sonnet.
What you can do after
Evaluate and choose a simple data type or structure for a task, then use a list to process document words.
How it connects
Connects data structures with data types, containers, strings, lists, functions, and document similarity.

Also explained in

Compare how 10 books explain data structure →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.