Command-line arguments
You may have noticed that, when you start some programs, you can provide them with inputs as the command line, for example, "ls examples", or "touch example3.py", or "chmod +x example2.py". This is because the operating system loader provides running programs with access to these command-line arguments. In Python it does this via a list, where the 0th argument is the name of the script, itself.To get access to this functionality, we need to "import" the system module. In other words, we need to ask the Python interpreter to make use of some code that is installed on the system, and organized as a module, but that we didn't write.
Let's see an example:
#!/usr/bin/python import sys if (len (sys.argv) == 1): print "Only the name of the program has been provided." else: print "There are " + str(len(sys.argv)) + " arguments, including the name of the script." print "The name of the script is " + sys.argv[0] + "." index = 1 while (index < len(sys.argv)): print sys.argv[index] index = index + 1 for argument in sys.argv: print argument
What are the take-aways?
- Access to command-line arguments requires "import sys"
- Command-line arguments are provided via a list called, "sys.argv"
- sys.argv[0] is the name of the python script's file
- Like any other List, the length can be found via "len()
- Arguments are strings, if you want numbers, you'll need to convert them by casting. The opposite is true for len(sys.argv), which is obviously an int.
Tuples
In an abstract sense, tuples are different than lists. But, in practice, as implemented in Python, they are essentially immutable Lists. I don't want to spend a lot of time on them, because that basically sums it up. They work the same way -- except that mutators, such as insert(), remove(), append(), etc, don't exist.About the only detail worth noting is that they are declared using ()-parenthesis, rather than []-brackets. An example is below:
Let's see an example:
#!/usr/bin/python person1 = ("Gregory Kesden", "Faculty", 1999) print person1[0] print person1[1] print person1[2] print "" for attribute in person1: print attribute
Choosing Tuples vs. Lists
From an under-the-hood perspective, one would expect tuples, where applicable, to be the more efficient and thereby preferable choice. In general, a simpler fixed-format data structure is smaller and can be represented internally in more efficient ways that one that might need to grow and has methods to support this.Having said that, in practice, this type of low-level optimization is rarely on the minds of Python programmers, who tend to be focused on rapid development, while maintaining correctness. To keep code digestable by everyone, they tend to have conventions and follow them, keeping it simple.
Consistent with the capabilities and conventions, most Python programmers would:
- Use lists rather than tuples, by necessity, any time it is best to be able to change the list, such as adding, removing, or changing items within it.
- Try to keep lists homogeneous, e.g. containing things only of one type, e.g. a list of names, a list of numbers, etc. These are the cases where the list contains a whole bunch of instances of exactly the same type of thing.
- Use tuples for heterogeneous applications, where the items within are not necessarily of the same type, as in our example, where it was a "tuple of properties describing something". Although one could conceivably view this as a "list of properties", most of us would tend to view it as a "bunch of attributes of a person". Note here, the attributes of something are often of heterogeneous types, such as, in our exampple above, string names and int years.
Sets
Sets are another type of collection. But, unlike lists and tuples, they are not ordered or indexed. Instead, they are just bags of things. In general, what one does with a set is put things in, take things out, and/or test to see whether or not something or things are members.Lists were created using []-brackets. Sets were created using ()-parentheses. Sets, oddly, are created using both! Their initial items are listed between ([ and ]). Also, note that, in the example below, the keyword set is required, unlike for lists, tuples, or dictionaries (later).
A single item can be added to a set using add(), a list of items can be added to a set using update(), and a single item can be removed using remove().
There are 4 key binary operations upon sets:
- | -- union (creates a new set with all of the members of both)
- & -- interesction (creates a new set with items in common between both)
- - -- difference (items uniquely in either set)
Let's look at an example:
#!/usr/bin/python instructors = set (["Greg", "Dave", "Adam", "Jamie", "Kelly"]) faculty = set (["Greg", "Dave", "Cohen", "Kamlet", "Rob"]) gradstudents = set (["Adam", "Jamie", "Kelly", "Richard", "Sarah", "Sam", "Rob"]) print "people" people = faculty | gradstudents print people print "" print "gradinstructors" gradinstructors = instructors & gradstudents print gradinstructors print "" print "facultyinstructors" facultyinstructors = instructors & faculty print facultyinstructors print "" print "gradAndFaculty" gradAndFaculty = faculty & gradstudents print gradAndFaculty print ""
Dictionaries
Dictionaries are a very useful collection. They store key-value pairs in the same way that, for example, a dictionary of words and definitions stores definitions associated with their words -- we look up the words to find the definitions.
Dictionaries, as a form of collection, store values indexed by keys. What I mean by "indexed by keys" is finable by looking up the key. Essentially, a Dictionary operates like a List -- except that you can pick the index for each item, rather than being limited to sequential integers.
As an aside, just in case you hear the phrase, in some languages, such as Perl, dictionaries are known as "associative arrays".
Like the syntax for lists used []-brackets, and tuples ()-parenthesis, dictionaries use {}-squiggly-brakcets.
Let's look at an example:
#!/usr/bin/python offices = { "Greg" : "GHC 7711", "Tom" : "GHC 4117", "Dave" : "GHC 5001" } # Look up a single name print "Greg's office is " + offices["Greg"] print "Tom's office is " + offices["Tom"] # Convert the Dictionary to a list, to get a list of keys keys = list(offices) for name in keys: print name # Iterate through the list to get the values for name in keys: print offices[name] # Remove Greg's entry print offices del offices["Greg"] print offices # Add a new entry offices["Gregory"] = "GCH 7711" print officesSome things to note:
- A :-colon separes the key from the value during initialization
- Items are removed with the "del" operator, which is an operator, not a function or method
- Items are added, just by making an assignment
- You can get a list of keys by casting the dictionary to a list
- You can get a list of values using list comprehensions, e.g "print [ offices[person] for person in offices ]"
- or, you can use .values() and/or .keys() and/or .items(), e.g. offices.keys() gives a list of the names, offices.values() gives a list of the office locations, and offices.items() gives a list of the (key,value) tuples, in this case, (name, location) tuples.