forked from UWPCE-PythonCert/IntroToPython-2014
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist_lab.py
More file actions
109 lines (75 loc) · 2.3 KB
/
list_lab.py
File metadata and controls
109 lines (75 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python
"""
Chris' solutions to the list lab
A couple take-home concepts:
If you need to delete stuff from the list when looping through it,
make a copy ([:]) first.
You almost never want to loop through a sequence by doing:
for i in range(len(seq)):
...
if you don't need the index, simply do:
for item in seq:
...
If you need both the item and the index, use enumerate():
for i, item in enumerate(seq):
...
If you need to loop through more than one list at once, use zip():
for item1, item2 in zip(list1, list2):
...
"""
# Task 1
fruits = ["Apples", "Pears", "Oranges", "Peaches"]
print fruits
new = raw_input("type a fruit to add> ")
fruits.append(new)
print fruits
ind = int(raw_input("give me an index> "))
print "you selected fruit number: %i, which is %s"%(ind, fruits[ind-1])
print fruits
fruits.insert(0, 'Kiwi')
print fruits
print "All the P fruits"
for fruit in fruits:
if fruit[0].lower() == 'p':
print fruit
# make a new list with duplicated entries - to test removal
d_fruits = fruits * 2
print " All the fruits are:", fruits
ans = raw_input("Which fruit would you like to delete? ")
while ans in d_fruits:
d_fruits.remove(ans)
print d_fruits
## another way to do that:
## This one only requires looping through list once
d_fruits = []
for fruit in fruits * 2:
if fruit != ans:
d_fruits.append(fruit)
print d_fruits
# keep a copy around for next step
orig_fruits = fruits[:]
for fruit in fruits:
ans = raw_input("Do you like: %s? "%fruit)
if ans[0].lower() == 'n': # so they could answer y or Y or yes or Yes...
while fruit in fruits: # just in case there are duplicates
fruits.remove(fruit)
elif ans[0].lower() == 'y':
pass
else:
print "please answer yes or no next time!"
# Note: I could be smarter about re-asking here,
# but that's not the point of this excercise...
print "here they are with only the ones you like"
print fruits
fruits = orig_fruits[:] # makes a copy
# option 1: build up a copy one by one:
r_fruits = []
for fruit in fruits:
r_fruits.append(fruit[::-1])
print "here they are reversed"
print r_fruits
# option 2: make a copy, then modify in place:
r_fruits = fruits[:]
for i, fruit in enumerate(r_fruits):
r_fruits[i] = fruit[::-1]
print r_fruits