Python Conditionals, Lists, Dictionaries, and Operators - Lists (Page 3 of 6 )
We covered variables in our previous tutorial. Now we are going to cover Lists. You may have heard of arrays in other programming languages; a list is the Python equivalent. Whereas a variable holds a value, a list holds a bunch of values. Each value can be referenced by its position in the list, starting with the number 0 and moving forward. Here is an example:
#!/usr/local/bin/python
suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']
print suess
print suess[0]
The above program creates a List named suess, and assigns a bunch of data to it, separating each piece of data with a comma (,). It then prints the entire List, and finally prints one element in the list, in this case the first one (0). Here it is!
I like green eggs and spam
I
You can also change the value of an element in a list later on:
#!/usr/local/bin/python
suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']
print “This is the data in the list originally:”, suess
suess[5] = 'ham'
print “This is the data in the list after the lawsuit:”, suess
Again, we fill up our suess List with data. Then we print it. Next, we change one specific element in the suess List from spam to ham (remember the first element is 0, so spam would be element 5). We then print it out with the new data, like so:
This is the data in the list originally: I like green eggs and spam
This is the data in the list after the lawsuit: I like green eggs and ham
The number of elements in a list is not a set number; you can add and delete elements until the cows come home. And let's face it, once those cows have had a taste of the good life, they are never returning to your crummy studio apartment.
#!/usr/local/bin/python
suess = ['I', 'like', 'green', 'eggs', 'and', 'spam']
print “This is the data in the list originally:”, suess
suess[6] = 'yummy!'
print 'Here is the list with appended elements:', suess
This results in:
This is the data in the list originally: I like green eggs and spam
Here is the list with appended elements: I like green eggs and spam yummy!
Next: Tuples >>
More Python Articles
More By James Payne