Teaching Kids Programming – List in Python


Teaching Kids Programming: Videos on Data Structures and Algorithms

Create a List in Python

List is a powerful object in Python. It can be used to store arrays of elements which do not need to be of same types.

a = []

Append Element(s) to a List

We can use the append method to insert an element to the end.

a.append(1) # a is now [1]
a.append(2) # a is now [1, 2]

We can also use the list concatenation to append another list to the end:

a += [3, 4] # a is now [1, 2, 3, 4]

Remove First or Last from List

We can use pop(0) to remove the first element in the list:

x = a.pop() # x is 1, a is now [2, 3, 4]

We can use pop() to remove the last element in the list:

x = a.pop() # x is now 4, a is now [2, 3]

Obtain Length of List

We can use the len() to obtain the number of the elements in the list:

x = len(a) # x = 2, because a has 2 elements [2, 3]

List Slicing in Python

We can use the [from:to] (from “from” inclusive to “to” exclusive) to do the array slicing in Python:

a = [0, 1, 2, 3, 4, 5, 6]
b = a[2:4] # b is [2, 3]
c = a[2:]  # c is [2, 3, 4, 5, 6]
d = a[:2]  # d is [0, 1]
e = a[-1]  # e is [6] last element

Useful List Built-in Functions

Get the min of the array/list.

a = [0, 1, 2, 3, 4, 5]
v = min(a) # v is 0

Get the maximum element of the array/list.

a = [0, 3, 5]
v = max(a) # v is 5

Get the sum of all the elements in the array/list.

a = [1, 2, 3, 4]
v = sum(a) # v is now 10 becaue 1+2+3+4=10

–EOF (The Ultimate Computing & Technology Blog) —

427 words
Last Post: Array Recursive Index Algorithm By Simulation
Next Post: Teaching Kids Programming - Check a Valid Parenthese String

The Permanent URL is: Teaching Kids Programming – List in Python (AMP Version)

Leave a Reply