← All lessons

Lesson 4

Data Structures and Functions in Python

Item 1

List

A list stores many values in one variable, inside square brackets. Lists are ordered and mutable (can be changed). Indexing starts at 0. Use append() to add and len() to count items.

List — Ordered, mutable collection: [1, 2, 3].
Index — Position of an item, starting at 0.
append() — Adds an item to the end.
len() — Returns the number of items.

Try it — edit the code and press Run:

Item 2

Tuples

A tuple is like a list but immutable — it cannot be changed after creation. Tuples use round brackets ( ).

Tuple — Ordered, immutable collection: (1, 2, 3).
Immutable — Cannot be changed.

Try it — edit the code and press Run:

Item 3

Dictionaries

A dictionary stores data as key: value pairs inside curly braces { }. You access a value using its key.

Dictionary — Collection of key: value pairs.
Key — The name used to look up a value.
Value — The data stored for a key.

Try it — edit the code and press Run:

Item 4

Function in Python

A function is a reusable block of code defined with def. It can take parameters and return a value. Functions make code organized and avoid repetition.

def — Keyword to define a function.
Parameter — Input variable of a function.
return — Sends a value back from the function.

Try it — edit the code and press Run:

Quick Quiz

1. What is the index of the first item in a list?

2. Which is a tuple?

3. Which method adds an item to the end of a list?

4. How do you get "Ali" from s = {"name": "Ali"}?

5. Which keyword defines a function?

Score: 0 / 5(Sign in to save your score)

Practice

Auto-checked exercises at three levels. Open hints one by one before the solution.

⭐Basic

Last item

colors = ["red", "green", "blue"]. Print the last item.

⭐⭐Intermediate

Square function

Write a function square(n) that returns n * n, then print square(6).

⭐⭐⭐Challenge

Sum a list

Write total(nums) that returns the sum of a list WITHOUT using sum(). Print total([4, 8, 15, 16]).

Smart Assistant Project

Task 4: Organize the Data

Goal: Store many students and reuse logic with functions.

Requirement: Store students in a list of dictionaries. Write a function get_grade(avg) and print each student's name with their grade.