Lists

We don’t have arrays; we have Python lists. Lists are super dynamic because they allow you to store more than one “variable” inside of them. Lists have methods that allow you to manipulate the values inside them. There is actually quite a bit to show you here so let’s get to it.

Example
sampleList = [1,2,3,4,5,6,7,8]
print (sampleList[1])
Result 2

The brackets are just an indication for the index number. Like most programming languages, Python’s index starting from 0. So, in this example 1 is the second number in the list. Of course, this is a list of numbers, but you could also do a list of strings, or even mix and match if you really wanted to (not the best idea though). Alright, now let’s see if we can print out the whole list.

Example
sampleList = [1,2,3,4,5,6,7,8]
for a in sampleList:
    print (a)
Result 1
2
3
4
5
6
7
8

I told you we would come back to see how awesome the for loop is. Basically, variable a is the actual element in the list. We are incrementing an implicit index. Don’t get too worried about it. Just remember we are cycling through the list.

Common List Methods

There are number of methods for lists, but we will at least cover how to add and delete items from them. All of the list methods can be found on Python’s documentation website. Methods follow the list name. In the statement listName.append(2), append() is the method.

  • .append(value) – appends element to end of the list
  • .count(‘x’) – counts the number of occurrences of ‘x’ in the list
  • .index(‘x’) – returns the index of ‘x’ in the list
  • .insert(‘y’,’x’) – inserts ‘x’ at location ‘y’
  • .pop() – returns last element then removes it from the list
  • .remove(‘x’) – finds and removes first ‘x’ from list
  • .reverse() – reverses the elements in the list
  • .sort() – sorts the list alphabetically in ascending order, or numerical in ascending order

Try playing around with a few of the methods to get a feel for lists. They are fairly straightforward, but they are very crucial to understanding how to harness the power of Python.

Dictionaries

Python’s dictionaries are not very common in other programming languages. At least at first, they don’t appear normal. Some super variables like lists, arrays, etc, implicitly have an index tied to each element in them. Python’s dictionary has keys, which are like these indexes, but are somewhat different (I’ll highlight this in just a second). Partnered with these keys are the actual values or elements of the dictionary. Enough with my terrible explanation, let’s go with an example.

Example
myExample = {'someItem': 2, 'otherItem': 20}
print(myExample['otherItem'])
Result 20

See, it’s a little weird isn’t it? If you tried to be an overachiever, you might have tried something like print(myExample[1]). Python will bite you for this. Dictionaries aren’t exactly based on an index. When I show you how to edit the dictionary, you will start to see that there is no particular order in dictionaries. You could add a key: value and, it will appear in random places.

A big caution here is that you cannot create different values with the same key. Python will just overwrite the value of the duplicate keys. With all of the warnings aside, let’s add some more key:values to our myExample dictionary.

Example
myExample = {'someItem': 2, 'otherItem': 20}
myExample['newItem'] = 400
for a in myExample:
    print (a)
Result newItem
otherItem
someItem

Isn’t that crazy how dictionaries are unordered? Now, you might not think they are unordered because my example returns alphabetical order. Well, try playing around with the key names and see if it follows your alphabetical pattern. It won’t. Anyways, adding a key:value is really easy. Simply put the key in the brackets and set it equal to the value. One last important thing about dictionaries.

Example
myExample = {'someItem': 2, 'otherItem': 20,'newItem':400}
for a in myExample:
    print (a, myExample[a])
Result (‘newItem’, 400)
(‘otherItem’, 20)
(‘someItem’, 2)

All we did here was to spit out our whole dictionary. In lists when we told Python to print our variable out (in our case, it’s a), it would print out the value. However, with dictionaries, it will only print out the key. To get the value, you must use the key in brackets following the dictionary’s name. Dictionaries are a little confusing, but they are well worth your patience. They are lightning fast and very useful after you start using them.

Formatting

We waited a little bit to talk about formatting because it might get a little intense with how much you can do and how easily you can do things with variables in Python. Formatting in Python is a little bit odd at first. But, once you get accustomed to it, you’ll be glad you did.

Formatting Numbers as Strings

Example
print('The order total comes to %f' % 123.44)
print('The order total comes to %.2f' % 123.444)
Result The order total comes to 123.440000
The order total comes to 123.44

Ya, I told you it’s a little weird. The f following the first % is short for float here because we have floating numbers and Python has a specific way of dealing with formatting decimals. The left % tells Python where you want to put the formatted string. The value following the right % is the value that we want to format. So, Python reads through the string until it gets to the first % then Python stops and jumps to the next %. Python takes the value following the second % and formats it according to the first %. Finally, Python places that second value where the first % is. We can use a single value such as a string or a number. We can also use a tuple of values or a dictionary. Alright, this is great, but what about formatting strings?

Formatting Strings

Strings are just like how we were formatting the numbers above except we will use a s for string instead of an f like before. Usually, you will only want to format a string to limit the number of characters. Let’s see it in action:

Example
a ="abcdefghijklmnopqrstuvwxyz"
print('%.20s' % a)
Result abcdefghijklmnopqrst

Strings

As with any programming language, strings are one of the most important things to know about Python. Also as we have experienced in the other languages so far, strings contain characters. Strings are not picky by any means. They can contain almost anything if used properly. The are also not picky by the amount of characters you put in them. Quick Example!

Example
myString = ""
print (type(myString))
Result <class ‘str’>

The type() is awesome. It returns the variable type of whatever is inside the parentheses, which is very useful if you have a few bugs that you can’t figure out or if you haven’t looked a large chunk of code for awhile and don’t know what type the variable is. Back to the amount of characters in a string, we can see even an empty set of “” returns as a string. Strings are powerful and are very easy to declare. Let’s look into some common string methods so you can get your hands dirty.

Common String Methods in Python

  • stringVar.count(‘x’) – counts the number of occurrences of ‘x’ in stringVar
  • stringVar.find(‘x’) – returns the position of character ‘x’
  • stringVar.lower() – returns the stringVar in lowercase (this is temporary)
  • stringVar.upper() – returns the stringVar in uppercase (this is temporary)
  • stringVar.replace(‘a’, ‘b’) – replaces all occurrences of a with b in the string
  • stringVar.strip() – removes leading/trailing white space from string

String Indexes

One of the really cool things about Python is that almost everything can be broken down by index and strings are no different. With strings, the index is actually the character. You can grab just one character or you can specify a range of characters.

Example
a = "string"
print (a[1:3])
print (a[:-1])
Result tr
strin

Let’s discuss the print (a[1:3]) because it is the easiest to explain. Remember that Python starts all indexes from 0, which would have been the ‘s’ in our variable a. So, we print out ‘tr’ because we printed everything up to our range of 3, but not 3 itself. As for the second example, welcome to a beautiful part of Python. Essentially, specifying a negative number after a : in an index means that you want python to calculate the index starting from the end and moving toward the front aka backwards. So, we tell python that we want everything from the first character to the second to last character. Take a breather, you earned it.

Writing to Files

Reading files is cool and all, but writing to files is a whole lot more fun. It also should instill a sense of danger in you because you can overwrite content and lose everything in just a moment. Despite the threat of danger, we press on. Python makes writing to files very simple. With somewhat similar methods to reading, writing has primarily 2 methods for writing. Let’s get to it!

Warning! The Evil “w” in the Open Method

Example
f = open("test.txt","w") #opens file with name of "test.txt"
f.close()

…And whoops! There goes our content. As I said, we are in dangerous water here friends. As soon as you place “w” as the second argument, you are basically telling Python to nuke the current file. Now that we have nuked our file, let’s try rebuilding it.

Example
f = open("test.txt","w") #opens file with name of "test.txt"
f.write("I am a test file.")
f.write("Maybe someday, he will promote me to a real file.")
f.write("Man, I long to be a real file")
f.write("and hang out with all my new real file friends.")
f.close()

If you were continuing from the last tutorial, we just rewrote the contents that we deleted to the file. However, you might be flipping out screaming, “but it’s not the same!” You are 100% correct my friend. Hit the control key a couple of times and cool off, I’ll show you the fix in a minute. Ultimately, the write() method is really easy. You just pass a string into it (or a string variable) and it will write it to the file following that one way process it does. We also noticed that it kept writing without using any line breaks. Let’s use another method to fix this.

Writing Lines to a File

We have the a fairly easy solution of just putting a new line character “\n” at the end of each string like this:

Example
f.write("Maybe someday, he will promote me to a real file.\n")

It’s just a simple text formatting character. Yes, even text files have a special formatting similar to how HTML documents have their own special formatting. Text files are just much more limited than HTML.

Appending to a File

Example
f = open("test.txt","a") #opens file with name of "test.txt"
f.write("and can I get some pickles on that")
f.close()

Boom! While our text file makes absolutely no sense to a human, we both know we just had a big victory. The only big change here is in the open() method. We now have an “a” (for append) instead of the “w”. Appending is really just that simple. Now go out there and write all over the world my friend.