Python quick bits

Just random Python quick bits to jar my memory

List

mylist=['item1','item2','3']
Index starts at 0
for myitem in mylist:
 code here
methods:
  • append()
  • pop()
  • extend() # append list of items ['item4','item5']
  • insert(position,"item6)remote("item2")

Dictionary

mydictionary={'tag1':'item1','tag2':'item2'}
Reference items by keys
for mykey in mydictionary.keys()
 code here

Object types in Python: int, dict, list, str
Testing for object type:
 isinstance(variable,type)
 var1='foo'
  isinstance(var1,str)

User input from the command line:
 import sys
 variable=raw_input("Enter user question here: ")

Length of list: len(list)

Strings

To work with strings: import string
mystring.split() # default delimeter is spaces with multiple spaces treated as one


for item in list:
  do something with item

for piece in string:
  do somethign with piece

Working with files

file1='/path/to/file'
with open(file1,'r') as afileobj:
  for line in afileobj:
    code
* 'r' is the file mode. Look for other modes here.



Comments

Popular posts from this blog

Database, schema, and table sizes in Greenplum

Greenplum update with multiple tables

Show running queries on Postgresql/Greenplum