Python: Lists

Go to Chapter 15 of A Smarter Way.

Let’s start out on this highly detailed page on handling lists:
http://introtopython.org/lists_tuples.html#Introducing-Lists

Create an empty list:

friends = []

Populate a list:

friends = ['bill', 'jeff', 'jim']

for friend in friends:
    print("Hello, " + friend.title() + "!")

A list in Python is defined inside square brackets.

Access an item using its index:

Remember these are 0-based arrays. The index goes inside square brackets:

friend = friends[1]
print(friend.title())

List count:

usernames = ['bernice', 'cody', 'aaron']
user_count = len(usernames)

print(user_count)

You don’t need to know how many items are in the list in order to get the last item; you use a negative number:

friend = friends[-1]
print(friend.title())

Iterate through all items on a list:

for friend in friends:
    print(friend.title())

Exercises

See http://www.asmarterwaytolearn.com/python/15.html

See http://introtopython.org/lists_tuples.html#Introducing-Lists

  1. Continue editing examples.py.
  2. Define a list. It can be your friends, your pets, your deadliest enemies.
  3. Print the first item from the list.
  4. Print the third item.
  5. Print all the elements of the list.