Docsity

Tuples - Computer Science - Lecture Notes, Study notes of Computer Science

Partial preview of the text

Download Tuples - Computer Science - Lecture Notes and more Study notes Computer Science in PDF only on Docsity!

Today

  • Quiz 8
  • File I/O (cont)
  • Tuples

Reading

  • Ch 14 pg. 125 (Tuples)
  • Ch 18 (Dictionaries)

Writing to files

Use write() to add text to a file

  • Must open the file for “writing” ...

def main():

open test.txt for writing to

outfile = open("test.txt", "w") outfile.write("spam\n") outfile.write("ham\n") outfile.write("eggs\n") outfile.close()

echo contents of test.txt

infile = open("test.txt", "r") for line in infile: print(line[:-1]) infile.close()

  • If the file does not exist, will be created (when in "w" mode)
  • Opening again for writing will “truncate” the file (erase previous contents)
  • To append (add to end of file), use "a" instead of "w"
  • Instead of outfile.write("...") can use print("...", file=outfile)

Can only write strings

  • so to write numbers, must convert to strings first (via str())

What you can’t do with a tuple:

>>> t[0] = 15 ... TypeError: ’tuple’ object does not support item assignment

You can do tuple assignment ...

>>> (a, b) = (10, 20)

>>> a + b 30

Tuples often useful data structures ...

  • For example, we can use tuples to represent objects like (x, y) points
  • Tuples used in some Python functions, e.g., you can “zip” together two lists

>>> z = zip([10, 20], [’a’, ’b’])

>>> list(z) [(10, ’a’), (20, ’b’)]

You can create tuples of length 1

>>> t = (10,) >>> len(t) 1

The parenthesis in tuples are optional (but standard to use)

>>> t = 10, 20

>>> type(t)

>>> a, b = t

>>> a + b 30

  • You’ll sometimes see assignments like this in Python:

x, y = 10, 20

  • But can make code hard to read ...

Q: What about this?

>>> my_list = [20, 10]

>>> my_list[0], my_list[1] = my_list[1], my_list[0]

>>> my_list [10, 20]

Q: How does this work?

  • Right-hand side evaluates to (10, 20)
  • Then assignment is made