Author Topic: SotK's Python Tutorials - Part 4: Lists, More Strings and For Loops  (Read 3724 times)

Son of the King

  • Megas Domestikos
    Voting Member
  • Posts: 3358
  • Karma: 29
  • Awards Awarded for outstanding services to Exilian!
    • View Profile
    • SotK
    • Awards
SotK's Python Tutorials
Part 4: Lists, More Strings and For Loops

Arrays, Lists and Tuples:

An array is simply a collection of other data types, for example it could be a collection of strings, a collection of integers etc. A 1-dimensional array can be imagined as just a column or row of numbers or other data, eg.

Code: (1-dimensional array) [Select]
(0, 1, 2, 3, 4, 5, 6)
Similarly, a 2-dimensional array could be imagined as a table of numbers, with rows and columns. This would be represented by what is effectively an array of arrays, so

Code: (2-dimensional array) [Select]
( (0, 1), (0, 2), (1, 1), (1, 2) )
Could be visualised by taking the big array to represent the columns, and each smaller array as the things in the columns:


You can see the first column contains the two numbers in the first position of the big array, and the second is the two number in the second position etc.

In most programming languages, arrays must contain data of all one type (you can have an array of integers, an array of strings, but not an array containing integers and strings). However, in Python an array can contain integers and strings and any data type you care to think of.

In Python, there are two types of arrays that you can use; Lists or Tuples. A list is an array which can be changed after it has been created (i.e. new stuff added onto it), and a tuple is an array which cannot be changed after it has been created (immutable).

To make a list in Python, you would use code like this:

Code: (Python List) [Select]
myList = [0, 1, 'some words', 982.23]
A list can also be created that contains nothing. This is a useful concept for initialising lists that are going to store things that are created at runtime.

Code: (Empty List) [Select]
emptyList = []
A tuple is created in exactly the same way, except using () instead of [].

We can 'index into' a list, to get the item in a certain position in the following way:

Code: (Getting an item from a list) [Select]
item = myList[2]
That will get the item in position 2 of myList. Bear in mind that the first item is in position 0, so position 2 is the third item in the list. In this case, item will be 'some words'.

More Strings

We have looked at strings as a data type for storing text, now we will look at things we can do to that text. A string in Python is basically a list, with each element (item) in the list being a character. This means that we can get individual characters from a string the same way as we do with lists. Since strings act like lists we can also loop through each character in a string, like we can loop through each item in a list (see next section).

We can also manipulate strings using string methods. A few examples of these are:

Code: (String Methods) [Select]
string = 'Hello World!'
lowerCase = string.lower()    # Puts the string in lower case
upperCase = string.upper()    # Puts the string in upper case
words = string.split()    # Splits the string into words stored in a list. You can pass a character to this method to split on a character other than space.
splitO = string.split('o')    # Splits the string wherever the character o appears

>>> print(words)
['Hello', 'World!']

>>> print(splitO)
['Hell', ' W', 'rld!']

For Loops

In the strings section, we mentioned looping through lists. This basically means making a loop which looks at each item in a list/tuple/array/whatever. Currently, we would use a while loop for that. We want to go look at each item, so we need to change which item we access each time we go through the loop:

Code: (Looping through a list with a while loop) [Select]
pos = 0
while pos < len(myList):
    pos += 1

The len(list) function returns the number of items in the list (this can also be used on a string to get its length). Since the list indices start at 0, the last item is position len(myList) - 1. However, there is an easier way!

Code: (For Loop) [Select]
for item in myList:

This does exactly the same as the while loop, but looks far neater. You can (and should!) use a for loop wherever you already know the amount of times you want to carry out a loop. For example, if we wanted to ask the user to enter 5 numbers and then show the average, we could use the following loop:

Code: (For Loop) [Select]
total = 0
for x in range(0, 5):
    num = int(input('Enter a number: '))
    total += num

print('Average is ' + str(total / 5))

There are a few functions here that I haven't mentioned.

  • range(x, y) - This returns a list of the numbers between x and y (x is included in the list, y is not)
  • input(x) - This prompts the user to enter some data. The prompt displayed is x.
  • int(x) - This converts x from whatever data type x is into an integer
  • str(x) - Similar to int(), but converts to string rather than to integer

In that example, x is just used as a counter so the loop executes the right number of times, similar to a while loop with a counter. However, in the first example item was a useful variable. Both types are useful, eg. looping through a list of sprites in a game.

Next, we will have some nice input!

<-- Part 3: While Loops
--> Part 5: User Input
« Last Edit: January 25, 2012, 07:26:18 PM by Son of the King »