SECTION 03 / 24

Join lists and add one new element

1 min read
The ++ operator joins two lists in order. To add one element x, wrap it in [x].
The ++ operator joins two lists in order. To add one element x, wrap it in [x].

In this course, ++ means list concatenation. If A = [1,13] and B = [2,17,1], A ++ B is [1,13,2,17,1]. No sorting or deduplication happens. A ++ B generally differs from B ++ A.

REAL COURSE DATA · BUILD AND UNPACK LISTS

Append and prepend list items

Follow one occurrence at a time. Choose another input to test empty lists, repeated IDs and different parameters.

Ready

CURRENT RECORD / VALUE

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Predict the next change, then step through the list. The original course records remain unchanged.

L = []
L = L ++ [3]       # [3]
L = L ++ [13]      # [3,13]
L = [25] ++ L      # [25,3,13]
L = L ++ [3]       # [25,3,13,3]

The brackets matter because ++ expects two lists. L ++ x is not valid when x is a single number. L ++ [x] adds x at the end; [x] ++ L adds it at the front. To keep a pair [ID,mark] together as one new element, use L ++ [[ID,mark]]. L ++ [ID,mark] adds two separate outer elements.

An expression computes a result; assignment stores it. Writing L ++ [3] without assigning the result does not by itself promise to update L. [] ++ L and L ++ [] give the same sequence as L.

Try it yourself

What is [3,13] ++ [13,25]?

Show explained answer

[3,13,13,25]. The repeated 13 stays in the list.

Try it yourself

How do you prepend 25 to [3,13]?

Show explained answer

[25] ++ [3,13], giving [25,3,13].

Try it yourself

How do you add the pair [3,53] as ONE outer element?

Show explained answer

Use L = L ++ [[3,53]]. The extra outer brackets wrap the pair into a singleton list.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑