Python Lists

I am in the process of learning the Python language and have been thinking of ways to help reinforce what I have learned. One thing that helps me in the learning process is to write about the subject I am learning. So I thought I would start a Python category on my personal blog and start documenting the journey I have been on. In my first post I focused on my interest in programming and using the main() function in Python programs (a tip my youngest enlightened me on). In my second post I cover how to open text files, read them and then close them. This post will be a multi-parter on lists.

From the very first program I worked on (a notes processing application) it became very apparent that I was going to be using a lot of lists. A list in Python is a group of things (strings, integers, etc...). Lists are quite malleable. You can have duplicate items in them and you can move, add or remove items on a whim. Lists are ordered so items can be identified or manipulated by their index number. The items of a list are encapsulated within brackets ([]).

fruit = ['apple','banana','orange']

In the example above I created a list of fruit. Fruit is the variable I have assigned the list using the equals sign. Inside the brackets are my list items: apple, banana and orange. The single quotes around each item in the list indicates that the items are strings, but the list could consist of integers as well. If you want to see the contents of a list you can use the print() method:

print(fruit)
['apple','banana','orange']

Once you have a list defined you can do interesting things like loop through them and compare items in the list to other things like strings. In future posts I will cover ways to update lists, retrieve values, loop through them, and run comparisons on list items with strings.