Study sheet: Python Strings and Lists

Course Outline

  1. String Fundamentals and Indexing
  2. String Immutability and Concatenation
  3. Formatted String Literals
  4. Lists and Element Access
  5. List Modification and Operations
  6. Tuples and Named Tuples
  7. Sets and Set Operations
  8. Dictionaries and Key-Value Mapping
  9. Common Python Data Types
  10. Type Conversions
  11. Binary Number Representation
  12. Health Data Calculations
  13. Python List Operations
  14. Python Set Operations

1. String Fundamentals and Indexing

Key Concepts & Definitions

  • String : A sequence of characters that represents textual data such as a name, location, or message.
  • String literal : A string defined in source code by surrounding its text with single or double quotes, such as 'MARY' or "MARY".

β˜… Must-know

  • A string is an ordered sequence whose first character has index 0, whose second character has index 1, and whose subsequent characters continue in order.

  • The length of a string is obtained with the built-in function len⁑(string)\operatorname{len}(string) and equals the number of characters in the string.

Further detail

  • An empty string is a sequence with 0 elements and is created with two quotes, as in str1 = "".

πŸ“Œ Negative string indices reference characters from the rightmost character, so alphabet[-1] refers to "Z" in the uppercase alphabet string.

Memory Hook

Create, measure, index: assign strings, use len(), then access characters by position.

2. String Immutability and Concatenation

Key Concepts & Definitions

  • String immutability : The property that a string object cannot have one of its characters changed in place.
  • String concatenation : Combining strings with the + operator to create a new string, such as "New" + "York" producing "NewYork".

β˜… Must-know

πŸ“Œ An assignment such as name[2] = "B" raises a TypeError because strings do not support item assignment.

  • To replace a string, assign the variable a new string object instead of modifying an indexed character.

Further detail

πŸ“Œ String concatenation accepts only string objects, so a number must first be converted with str(), as in str(332) + " Main Street".

Memory Hook

Strings cannot be changed in place, whereas concatenation creates a new string.

3. Formatted String Literals

Key Concepts & Definitions

  • Formatted string literal : A string beginning with f before its quote and using curly braces for expressions whose values replace the expressions in the output.

β˜… Must-know

  • The f-string f"{num_items} tacos cost {cost_taco * num_items}" evaluates both replacement fields and can produce "3 tacos cost 3.75" when num_items is 3 and cost_taco is 1.25.

πŸ“Œ A format specification follows a colon inside a replacement field and controls how the evaluated value is represented, such as {4:.2f} producing 4.00.

Further detail

πŸ“Œ Adding an equals sign after an f-string expression prints both the expression and its result, so f"{24=}" produces "24=8".

πŸ“Œ Double braces in an f-string produce literal curly braces, so f"{{Jeff Bezos}}: Amazon" produces "{Jeff Bezos}: Amazon".

  • Common f-string presentation types include:
    • s for strings
    • d for decimal integers
    • b for binary
    • x or X for hexadecimal
    • for exponent notation
    • f for fixed-point notation

Memory Hook

An f-string is a template with curly-braced expression slots filled during execution.

4. Lists and Element Access

Key Concepts & Definitions

  • List : A mutable, ordered collection created by surrounding a sequence of values with brackets, such as [10, "abc"].

β˜… Must-know

  • List elements are ordered by index beginning at 0, and an empty list is created with [].

πŸ“Œ A list index must be an integer; using a floating-point index such as 0.0 or 1.0 causes a runtime error.

  • A list element is accessed with bracket notation such as my_list[i], where i identifies the element's integer index.

Further detail

  • A list can contain values of different data types, such as the integer 1, floating-point value 2.5, and string "abc" in [1, 2.5, "abc"].

Memory Hook

Strings are immutable sequences, whereas lists are mutable ordered collections.

5. List Modification and Operations

Key Concepts & Definitions

  • Sequence-type function : A built-in function that accepts a sequence such as a list or string without requiring an object-dot notation, as with len(my_list).

Essential Points

πŸ“Œ Because lists are mutable, assigning a value to a position such as prices[0] = 2.50 updates that list element.

  • The append(), pop(), and remove() methods modify lists by adding an element, removing an indexed element, and removing the first matching value, respectively.

  • Useful list operations include:

    • len(list) for length
    • list1 + list2 for concatenation
    • min(list) and max(list) for extreme values
    • sum(list) for the sum of numeric elements
    • list.index(val) for the first matching index
    • list.count(val) for the number of occurrences

πŸ“Œ The min() and max() functions require all list elements to have the same type, while sum() operates on numbers only.

Memory Hook

Append adds at the end, pop removes by index, and remove deletes by value.

6. Tuples and Named Tuples

Key Concepts & Definitions

  • Tuple : an immutable sequence that stores a collection of data whose elements cannot be changed after creation
  • Named tuple : a simple immutable data type whose fields have names that can be accessed with dot notation

Essential Points

  • A tuple is typically written as comma-separated values surrounded by parentheses, such as (5, 15, 20), and supports len(), indexing, and other sequence functions.

  • The tuple white_house_coordinates = (38.8977, 77.0366) stores latitude at index 0 and longitude at index 1.

  • πŸ”„ Creating a named tuple involves these steps:

    1. Import namedtuple from collections
    2. Define the type with a name and field names
    3. Call the type with values to create an object

Memory Hook

Lists can change; tuples cannot.

7. Sets and Set Operations

Key Concepts & Definitions

  • Set : a mutable unordered collection of unique elements

β˜… Must-know

πŸ“Œ Passing a list containing duplicate values to set() creates a set in which the duplicates are omitted.

  • Set modification methods include:
    • add() for one value
    • update() for elements from another set
    • remove() for a specified value
    • pop() for a random element
    • clear() for all elements

πŸ“Œ The intersection contains elements common to all specified sets, the union contains all unique elements, the difference contains elements in the first set but not the others, and symmetric_difference contains elements appearing in exactly one of two sets.

Further detail

πŸ“Œ A set can be created with set(iterable) or with comma-separated elements inside braces, while an empty set must be created with set().

Memory Hook

A bag of unique items with no numbered slots.

8. Dictionaries and Key-Value Mapping

Key Concepts & Definitions

  • Dictionary : a mutable mapping that associates keys with values

β˜… Must-know

πŸ“Œ A dictionary entry is accessed with its key in brackets, and using a key that does not exist raises a KeyError.

  • Dictionary assignment adds a new key-value pair when the key is absent and replaces the existing value when the key is already present, while del dict[key] removes an entry.

Further detail

πŸ“Œ Dictionary keys must be immutable types such as numbers, strings, or tuples, while dictionary values can be any type.

Memory Hook

Lists use positions; dictionaries use keys.

9. Common Python Data Types

β˜… Must-know

  • The common container types are:
    • string
    • list
    • tuple
    • set
    • dictionary

πŸ“Œ A list is mutable and ordered, whereas a tuple is immutable and ordered.

πŸ“Œ A programmer generally uses a list for ordered data that may change, a tuple for ordered data that should not change, and a dictionary for relationships between keys and values.

Further detail

πŸ“Œ Sequence types such as strings, lists, and tuples support indexing with brackets and the len() function.

Memory Hook

N-L-T-S-D: numeric, list, tuple, set, dictionary.

10. Type Conversions

Key Concepts & Definitions

  • Type conversion : the conversion of a value from one data type to another

β˜… Must-know

πŸ“Œ An arithmetic operation produces a float if either operand is a float; otherwise, adding or multiplying integers produces an integer.

πŸ“Œ Converting a float to an integer with int() truncates the fractional part, so int(4.9) produces 4.

  • The conversion functions int(), float(), and str() create integers, floating-point values, and strings respectively, and input() initially returns a string that must be converted before numeric use.

Further detail

  • The expression int("500") produces the integer 500, while float("1.75") produces the floating-point value 1.75.

Memory Hook

input string β†’ int or float β†’ calculation

11. Binary Number Representation

Key Concepts & Definitions

  • Binary number : represents a value in base 2 using only the digits 0 and 1
  • Binary number : uses base 2, with digits 0 and 1 weighted by increasing powers of 2.
  • Decimal number : uses base 10, with digits from 0 through 9 weighted by increasing powers of 10.

β˜… Must-know

  • Each position in a binary number is weighted by an increasing power of 2, while each position in a decimal number is weighted by an increasing power of 10.

  • An 8-bit unsigned binary number can represent values from 0 through 255, making 255 the largest integer representable with 8 bits.

  • To convert a binary number to decimal, multiply each binary digit by its corresponding power of 2 and add the resulting values.

Further detail

  • A computer stores numbers using bits, and the finite number of bits allocated to a variable limits the range of values it can represent.

  • To convert a decimal number to binary, select the powers of 2 whose sum equals the decimal value and write 1 in those positions and 0 in the others.

Memory Hook

Decimal uses powers of 10; binary uses powers of 2.

12. Health Data Calculations

β˜… Must-know

πŸ“ Formula β€” The program estimates age in days by multiplying the user's age in years by 365: ageΒ inΒ days=ageΒ inΒ yearsΓ—365\text{age in days} = \text{age in years} \times 365.

  • The health-data practice asks the programmer to calculate age in minutes and seconds, estimate lifetime heartbeats using an average rate of 72 beats per minute, estimate lifetime sneezes, estimate lifetime calories and equivalent food items, and add other researched health statistics.

Further detail

  • For an input age of 3 years, multiplying by 365 produces an age of 1,095 days.

Memory Hook

Years β†’ days β†’ minutes and seconds β†’ lifetime estimates

13. Python List Operations

β˜… Must-know

  • A list-basics program creates my_list and your_list in input order, concatenates them into our_list, appends their_flower, replaces my_flower2 with their_flower, removes the first occurrence of their_flower without using index(), and removes the second element.

  • List concatenation with the + operator combines the elements of my_list followed by the elements of your_list.

Further detail

  • With inputs rose, peony, lily, rose, daisy, and aster, concatenating the first two lists produces ['rose', 'peony', 'lily', 'rose', 'daisy'].

Memory Hook

Define β†’ concatenate β†’ append β†’ replace β†’ remove β†’ delete

14. Python Set Operations

Key Concepts & Definitions

  • Set : a collection that stores unique elements without preserving list-style order.

β˜… Must-know

  • A set-basics program initializes fruits with three inputs, adds two more fruits, adds their_fruit, adds your_fruit1 again, and removes my_fruit1.

Further detail

  • Adding an element that is already present in a set does not create a duplicate or change the set's contents.

  • For the inputs apple, peach, lemon, apple, pear, and plum, the sorted set output after initialization is ['apple', 'lemon', 'peach'].

Memory Hook

Lists preserve order and duplicates, whereas sets keep unique elements.

Synthesis Tables

Strings and Lists

PropertyStringsLists
MutabilityImmutableMutable
OrderingCharacters have indices starting at 0Elements have indices starting at 0
ModificationReassign the variable to replace the stringAssign, append, pop, or remove elements

Python Container Types

TypeOrderingMutability or association
listOrderedMutable
tupleOrderedImmutable
setUnorderedUnique elements
dictionaryKey-basedKey-value associations

Test your knowledge

Test your knowledge on Python Strings and Lists with 44 multiple-choice questions with detailed corrections.

1. Which kind of data does a string represent in Python?

2. Which expression is a string literal written directly in source code?

Take the quiz β†’

Review with flashcards

Memorize the key concepts of Python Strings and Lists with 89 interactive flashcards.

What is a string in programming?

A sequence of characters representing textual data.

How is a string literal defined in source code?

By surrounding text with single or double quotes.

What index does the first character of a string have?

Index 0.

See flashcards β†’

Similar courses

Create your own study sheets

Import your course and AI generates sheets, quizzes and flashcards in 30 seconds.

Sheet generator