Dec. 7, 2012, 6:43 p.m. by Rosalind Team
Topics: Introductory Exercises, Programming
Strings and lists
We've already seen numbers and strings, but Python also has variable types that can hold more than one piece of data at a time. The simplest such variable is a list.
You can assign data to a list in the following way:
list_name = [item_1, item_2, ..., item_n]. The items of the list can be of any other type: integer, float, string. You even explore your inner Zen and make lists of lists!Any item in a list can be accessed by its index, or the number that indicates its place in the list. For example, try running the following code:
tea_party = ['March Hare', 'Hatter', 'Dormouse', 'Alice'] print tea_party[2]Your output should be:
DormouseNote that the output was not
Hatter, as you might have guessed. This is because in Python, indexing begins with 0, not 1. This property is called 0-based numbering, and it's shared by many programming languages.You can easily change existing list items by reassigning them. Try running the following:
tea_party[1] = 'Cheshire Cat' print tea_partyThis code should output the list with "Hatter" replaced by "Cheshire Cat":
March Hare, Cheshire Cat, Dormouse, AliceYou can also add items to the end of an existing list by using the function
append():tea_party.append('Jabberwocky') print tea_partyThis code outputs the following:
March Hare, Cheshire Cat, Dormouse, Alice, JabberwockyIf you need to obtain only some of a list, you can use the notation
list_name[a:b]to get only those from indexaup to but not including indexb. For example,tea_party[1:3]returnsCheshire Cat, Dormouse, notCheshire Cat, Dormouse, Alice. This process is called "list slicing".If the first index of the slice is unspecified, then Python assumes that the slice begins with the beginning of the list (i.e., index 0); if the second index of the slice is unspecified, then you will obtain the items at the end of the list. For example,
tea_party[:2]returnsMarch Hare, Cheshire Catandtea_party[3:]returnsAlice, Jabberwocky.You can also use negative indices to count items backtracking from the end of the list. So
tea_party[-2:]returns the same output astea_party[3:]:Alice, Jabberwocky.Finally, Python equips you with the magic ability to slice strings the same way that you slice lists. A string can be considered as a list of characters, each of which having its own index starting from 0. For example, try running the following code:
a = 'flimsy' b = 'miserable' c = b[0:1] + a[2:] print cThis code will output the string formed by the first character of
miserableand the last four characters offlimsy:mimsy
Given: A string
Return: The slice of this string from indices
HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain. 22 27 97 102
Humpty Dumpty