+91 81900 98289

Lists and Arrays

This Lists and Arrays lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.

A Python list is the array you will use most. Indexing is fast. Inserting at the front moves every later item.

Store items that you read by position in a list. Store items that you read by name in a dict.

Example 1: Start here

append is cheap. insert(0, value) is not, once the list is long.

items = ["Python", "SQL", "Git"] # a list; the values stay in this order print(items[1]) items.append("Excel") # add one item at the end of the list print(items)

Example 2: Walk the values

Lists and Arrays starts by visiting one value at a time. Read the printed lines from top to bottom.

values = [21, 3, 11, 7] # a list; the values stay in this order for value in values: # repeat the indented lines once per value print(value)

Example 3: Keep the largest

Many data-structure lessons reduce a list to one answer. This one remembers the largest number seen so far.

values = [21, 3, 11, 7] # a list; the values stay in this order best = values[0] # the first value for value in values: # repeat the indented lines once per value if value > best: # run the indented lines only when this is true best = value # another name for the same value print(best)

Example 4: Search for a target

A search asks one yes-or-no question: is the target in the collection? Lists and Arrays builds on that question.

values = [3, 21, 11] # a list; the values stay in this order target = 21 # a whole number print(target in values) # in is True when the value is found
append is cheap. insert(0, value) is not, once the list is long.
Call Now 81900 98289