Arrays (Lists) in Python

Arrays (Lists) in Python

Data Structure Needed

Need some way to hold onto all the individual data items after processing them making individual identifiers x1, x2, x3,… is not practical or flexible the answer is to use an ARRAY a data structure – bigger than an individual variable or constant

An Array (a List)

You need a way to have many variables all with the same name but distinguishable!
In math they do it by subscripts or indexes
x1, x2, x3 and so on
In programming languages, hard to use smaller fonts, so use a different syntax
x [1], x[0], table[3], point[i]

Indexing an Array

The index is also called the subscript.In Python, the first array element always has subscript 0, the second array element has subscript 1, etc.Subscripts can be variables – they have to have integer values k = 4
items = [3,9,’a’,True, 3.92]
items[k] = 3.92
items[k-2] = items[2] = ‘a’

List Operations

Lists are often built up one piece at a time using append.nums = []x = float(input(‘Enter a number: ‘))while x >= 0: nums.append(x) x = float(input(‘Enter a number: ‘))
Here, nums is being used as an accumulator, starting out empty, and each time through the loop a new value is tacked on.

Using a variable for the size

It is very common to use a variable to store the size of an array
SIZE = 15
arr = []
for i in range(SIZE):
arr.append(i)
Makes it easy to change if size of array needs to be changed

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *