Functions, Lists & Strings

Data Structures & Algorithms · First Steps · Basics · 14 min

Reusable recipes (functions) and the two data types you'll use in every interview.

A vending machine labelled title_case. You drop in "hello big world", gears split it into words, a tiny stamp capitalises each first letter, and "Hello Big World" drops out of the slot.

The idea in everyday words

A function is a vending machine: you put something in (inputs), it does its job inside, and something comes out (return value). You don't care HOW it works inside: you just press the button again whenever you need it.

Functions: write once, use forever

A function has a name, inputs (parameters) and a return value. Press Run, then change the numbers and run again:

def area(width, height):
    return width * height

print(area(3, 4))
print(area(10, 2))

Rule of thumb: if you copy-paste code twice, make it a function.

Lists: a numbered row of things

Lists keep items in order. Index starts at 0; -1 means "last".

fruits = ["apple", "banana", "cherry"]
print(fruits[0], fruits[-1])
fruits.append("mango")      # add at end
print(len(fruits), fruits)
print(fruits[1:3])          # slice: index 1 up to (not incl.) 3

Strings: lists of characters

You can loop over a string, slice it and reverse it.

word = "interview"
print(word.upper())
print(word[::-1])           # reversed
vowels = 0
for ch in word:
    if ch in "aeiou":
        vowels += 1
print("vowels:", vowels)

Same thing in JavaScript:

const word = "interview";
console.log(word.toUpperCase(), word.split("").reverse().join(""));
console.log([...word].filter((c) => "aeiou".includes(c)).length);

Step by step

  1. Call:

    area(3, 4) → width = 3, height = 4

  2. Inside:

    compute 3 * 4 = 12

  3. Return:

    the call is replaced by 12 → print(12)

Code example

def count_vowels(text):
    return sum(1 for ch in text.lower() if ch in "aeiou")

for w in ["Apple", "sky", "Education"]:
    print(w, count_vowels(w))

Complexity

  • Time: O(n) for a loop over a string
  • Space: O(1)

Interview tips

  • Clarify upper/lower case and spaces in string questions.

  • Reversing and counting characters are warm-up questions.

  • In Java use StringBuilder for building strings in loops.

Challenge: Capitalize Every Word

Return the sentence with the first letter of every word in upper case (words are separated by single spaces).

Example: title_case("hello big world") → "Hello Big World"

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in First Steps

Previous: Python Crash Course for DSA · Next: Classes & Objects