Python Introduction | Lists, Tuples, Ranges, Sets, and Dictionaries | Arrays and Lists

Most programming languages provide a special variable-like feature for grouping many values together. It is generally called an array. An array manages values by number. For example, you can change value number 1 or retrieve value number 3.

Python provides this feature with a list. Write a list as follows.

variable = [value1, value2, ...]

Write comma-separated values inside square brackets. This creates an ordered list whose values have numbers called indexes.

The important point is that indexes start at 0. The first value is number 0, the second is number 1, and the third is number 2. A list containing ten values has indexes from 0 through 9, not 1 through 10.

To access an individual list element, write variable[number].

arr[0] = "OK"
val = arr[1]

This syntax lets you change or retrieve the element at a specified index.

Consider the following example.

arr = ['hello','welcome','good-bye']
for n in arr:
    print(n)
 
print("....end.")

This code uses the previously introduced for ... in ... syntax to iterate over every list element.

for variable in list:

The loop retrieves each value from the list in order and assigns it to the variable. Lists and for statements are frequently used together, so remember both.