Title | Kinds of Collections - Professor Dill |
---|---|
Author | Mary Berry |
Course | Intro to Programming |
Institution | University of Virginia |
Pages | 3 |
File Size | 55.6 KB |
File Type | |
Total Downloads | 89 |
Total Views | 136 |
Professor Dill...
Sunday, October 13, 2019
12:49 PM
Kinds of Collections • Order matters, repetition okay: ○ String ○ List ○ Tuple ○ Range • Counting starts at 0 • Collection (index) gives a specific value from the collection
Range(x): • Gives all integers from 0 (inlcusive) to x (exclusive • Range(5) -> 0, 1, 2, 3, 4, Range(x, y): • fives all integers from y (inclusive) to x (exclustive) • Range(2, 6) --> 2, 3, 4, 5 Range(y, x, z): • Gives all integers from y (inclusive) to x (exclusives), but it takes only every zth number Strings Collection of characters Order matters Repetition is okay Index - number that represnets a X = 'hello' X[i] gives the Ith character in the string (starts at 0)
Indexing S = 'bananarama' Indexing S = 'bananarama' Indices are always ints • S[1.0] gives an error Start counting at 0: • S[0] is 'b' ○ Read as "s sub 0" ○ Read s "s of 0" • S[1] is 'a' • S[2] is 'n' Len(s) gives the number of things in the collection • Len(s) is 10 Use negative indices to count from the end List • A way of collecting together a nunch of things, and giving them all one name • [the things separated by commas] My_list = [1, 2, 3, 4] My_list = ['one', 'two', 'three', 'four'] My_list = [1, 'two', 3, 'four'] Len(my_list) gives the number of things in the list My_list[i] gives the ith thng in the list (starting at 0)
Indexing: how to get one thing out of a collection Slicing: how to get a chunk out of a collection • Give it a start index and an end index • Evaluates to a new collection from start (inclusive) to end (exclusive) S[start:end] • Gives the chunk of s starting from index start(inclusive) and ending with index end (exclusive) S[start:]
• Gives the chunk of s starting from the index start(inclusive) and ending at the end of the collection S[:end] • Gives the chunk of s starting from the beginning, and ending at index end(exclusive) S[start:end:step] • Extended slice • Gives a chunk of s starting from index start(inclusive), ending at index end • Gives a chunk of s starting from index start(inclusive), ending at index end (exclusive), keeping every stepth item
If leave off start: assign 0 to that posititon If leave off end: assign len(s) Leave off step: assign 1...