Checklist of Understanding Lists and Dicts¶
Accessing a simple list¶
Start off with the variable mylist
set to this list:
mylist = ['oranges', 'pears', 'kiwis', 'apples', 'eggs' ]
Questions¶
- Get the number of elements in the
mylist
. - Get the first element in the
mylist
. - Get the last element in the
mylist
- Get the second element in the
mylist
- Get the second to last element in the
mylist
- Make a slice (i.e. sublist) of
mylist
, beginning with the 3rd element. - Make a slice of
mylist
, beginning with the 2nd element, through the 2nd-to-last element.
Expected results¶
- Get the number of elements in the
mylist
.
5
- Get the first element in the
mylist
.
THING
- Get the last element in the
mylist
THING
- Get the second element in the
mylist
THING
- Get the second to last element in the
mylist
THING
- Make a slice (i.e. sublist) of
mylist
, beginning with the 3rd element.
THING
- Make a slice of
mylist
, beginning with the 2nd element, through the 2nd-to-last element.
THING
Solutions¶
- Get the number of elements in the
mylist
.
>>> len(mylist)
5
- Get the first element in the
mylist
.
>>> mylist[0]
mylist[0]
- Get the last element in the
mylist
>>> mylist[-1]
THING
- Get the second element in the
mylist
>>> mylist
THING
- Get the second to last element in the
mylist
>>> mylist
THING
- Make a slice (i.e. sublist) of
mylist
, beginning with the 3rd element.
>>> mylist
THING
- Make a slice of
mylist
, beginning with the 2nd element, through the 2nd-to-last element.
>>> mylist
THING
Looping through a list¶
Questions¶
- Print out each element in
mylist
, but in upper-case. - Count the number of elements in
mylist
using a for-loop (i.e. without usinglen
) - Get the sum of the lengths of each element (i.e. character length) in
mylist
Sorting a list with sorted()¶
- Make a new copy of
mylist
, except with the elements sorted in alphabetical order. - Make a new copy of
mylist
, except with the elements sorted in reverse-alphabetical order - Make a copy of
mylist
with the elements sorted by length, shortest to longest. - Make a copy of
mylist
with the elements sorted by length, longest to shortest
5. Make a copy of mylist
with the elements sorted by length, longest to shortest, and in case of a tie, in alphabetical order.
6.