Python lists by example

Starter task:

Write a program to do this:

Enter a number: 345
Enter a number: 3568
Enter a number: 2345
Enter a number: 4524
Enter a number: 362
Enter a number: 675
Enter a number: 2
Enter a number: 5467
Enter a number: 381
Enter a number: 155
The numbers you entered were:
345
3568
2345
4524
362
675
2
5467
381
155

Study the output of my shell session carefully. It should teach you all you need to know about lists.

Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:06:53) [MSC v.1600 64 bit (AMD64)] on win32Type "copyright", "credits" or "license()" for more information.
>>> myList = []
>>> print(myList)
[]
>>> myList.append("Hello")
>>> print(myList)
['Hello']
>>> myList.append(3)
>>> print(myList)
['Hello', 3]
>>> anotherList = ["Goodbye", 2]
>>> myList.extend(anotherList)
>>> print(myList)
['Hello', 3, 'Goodbye', 2]
>>> print(myList[2])
Goodbye
>>> myList[2]="Farewell"
>>> print(myList)
['Hello', 3, 'Farewell', 2]
>>> myList.insert(3, 99)
>>> print(myList)
['Hello', 3, 'Farewell', 99, 2]
>>> myList.remove(99)
>>> print(myList)
['Hello', 3, 'Farewell', 2]
>>> del myList[2]
>>> print(myList)
['Hello', 3, 2]
>>> print(myList[0:1])
['Hello']
>>> print(myList[0:2])
['Hello', 3]
>>> print(myList[:2])
['Hello', 3]
>>> print(myList[1:])
[3, 2]
>>> numList = [4, 2, 8, 6, 9, 1, 7, 3, 5]
>>> print(numList)
[4, 2, 8, 6, 9, 1, 7, 3, 5]
>>> print(sorted(numList))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(numList)
[4, 2, 8, 6, 9, 1, 7, 3, 5]
>>> numList.sort()
>>> print(numList)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> for blah in numList
SyntaxError: invalid syntax
>>> for blah in numList:
       print("Element is ", blah)

Element is  1
Element is  2
Element is  3
Element is  4
Element is  5
Element is  6
Element is  7
Element is  8
Element is  9
>>> print("Hello"[1:3])
el
>>> print(list("Hello"))
['H', 'e', 'l', 'l', 'o']
>>>

Practice tasks:

  • Rewrite the starter program using for loops and a list
  • Write a program that asks for six words and prints them in alphabetical order
  • Write a program that prints a multiplication table for any number that you want
  • Write a program that asks for two words and prints true if they are anagrams and false if they are not
    (Believe it or not, this last program can be written in ONE LINE of Python code…)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s