Strings, Lists, and Ranges

Sequence Operations Review

The following operations work on any sequence in Python (strings and lists).

Strings

"a" in "aeiou"  # in operator
True
"b" not in "aeiou" # not in operator
True
"CS" + "134" # concatenation with +
'CS134'
"abc" * 3 # * operator
'abcabcabc'
myString = "abc" 
myString[1]  # indexing with []
'b'
myString[1:2] # slicing with [:]
'b'
# using negative step in slicing
myString[::-1] 
'cba'
len(myString) # length function
3
# min function (finds smallest character)
min(myString) 
'a'
# max function (finds largest character)
max(myString) 
'c'

Lists

1 in [1, 2, 3] # in operator
True
1 not in [1, 2, 3] # not in operator
False
[1] + [2] # concatenation with + 
[1, 2]
[1, 2] * 3 # * operator
[1, 2, 1, 2, 1, 2]
myList = [1, 2, 3]
myList[1] # indexing with []
2
myList[1:2] # slicing with [:]
[2]
# slicing with negative step
myList[::-1] 
[3, 2, 1]
len(myList)  # len function
3
min(myList)  # min function
1
max(myList) # max function
3

list( ) Function

Similar to other types that we have seen: integer, float and string, there is a built-in function with the name of the type that generates values of that types by converting from a type to another.

Using list() on strings.

The list function, if given a string, returns a list of all its constituent characters (in order).

word = "Computer Science!"
list(word) # can turn a string into a list of its characters
['C',
 'o',
 'm',
 'p',
 'u',
 't',
 'e',
 'r',
 ' ',
 'S',
 'c',
 'i',
 'e',
 'n',
 'c',
 'e',
 '!']
list(str(3.14159265))
['3', '.', '1', '4', '1', '5', '9', '2', '6', '5']

Appending to Lists

There are two ways to add items to a list. We have already seen how we can concatenate with the + operator. This actually creates a new list and returns it, similar to string concatenation. Unlike strings, however, lists are mutable, which means they can be modified. To add an item to an existing list, we can use the list append() method.

numList = [1, 2, 3, 4, 5]
numList + [6]
[1, 2, 3, 4, 5, 6]
numList # numList has not changed
[1, 2, 3, 4, 5]
numList.append(6)
numList # numList has been updated to include 6
[1, 2, 3, 4, 5, 6]

More Useful List Methods

  • myList.extend(itemList): appends all the items in itemList to the end of myList (modifying myList)

  • myList.count(item): counts and returns the number (int) of times item appears in myList

  • myList.index(item): returns the first index (int) of item in myList if it is present, else throws an error

myList = [1, 7, 3, 4, 5]
myList.extend([6, 4])
myList
[1, 7, 3, 4, 5, 6, 4]
myList.count(4)
2
myList.index(3)
2
myList.index(10)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
/var/folders/md/kwd9nc_d2ns0hw9wsvdrnt2c0000gn/T/ipykernel_98464/861320968.py in <module>
----> 1 myList.index(10)

ValueError: 10 is not in list

Useful String Methods for working with Lists

It is often useful to be able to convert strings to lists, and lists to strings.

.split() method. When the split() method is called on a string of words, it breaks up the words (by default at blank spaces) and returns a list of the words

.join() method. Given a list of strings, the .join() string method, when applied to a character char, concatenates the strings in the list together with the character char between them and returns a string

.strip() method. strip() remove leading and trailing whitespace characters (including blank spaces and new lines) from a string and returns a new string

phrase = "What a lovely day"
phrase.split()
['What', 'a', 'lovely', 'day']
newPhrase = "What a *lovely*     day!"  # multiple spaces or punctuations dont matter
newPhrase.split(" ")
['What', 'a', '*lovely*', '', '', '', '', 'day!']
commaSepSpells = "Impervius, Portus, Lumos, Reducio, Protego" #comma separated strings
commaSepSpells.split(',')
['Impervius', ' Portus', ' Lumos', ' Reducio', ' Protego']
wordList = ['Everybody', 'is', 'looking', 'forward', 'to', 'the', 'weekend']
'*'.join(wordList)
'Everybody*is*looking*forward*to*the*weekend'
'_'.join(wordList)
'Everybody_is_looking_forward_to_the_weekend'
' '.join(wordList)
'Everybody is looking forward to the weekend'
word = "  ****Snowy Winters**  "
word.strip()
'****Snowy Winters**'
word = '\nHello world\n'
word
'\nHello world\n'
word.strip()
'Hello world'

Range sequences

Python provides an easy way to iterate over common numerical sequences through the range data type. We create ranges using the range() function.

range(0,10)
range(0, 10)
type(range(0, 10))
range

In Python 3, we don’t have an easy way to display the numbers stored in a range object. If we want to examine the contents of a range object, we can pass the object into the function list() which returns a list of the numbers in the range object.

Similar to other types that we have seen, such as integers, floats and strings, the built-in function list() converts values and other data types into a list.

Using list() on range objects:

The list() function, when given a range object, returns a list of the elements in that range. This is convenient for see what a range object actually consists of.

list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Notice. The range(firNum, secNum) represents all numbers from firNum through secNum - 1. If the firNum is 0, we can omit. For example:

list(range(-10, 10))
[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list(range(3))
[0, 1, 2]

Looping over ranges

Range functions provide us with an iterable sequence, which we can loop over, just like we did with strings and list.

What are some reasons why we might want to loop over a range of numbers?

for i in range(1, 11):  # simple for loop that prints numbers 1-10
    print(i)
1
2
3
4
5
6
7
8
9
10
# what does this print?

for i in range(5):  
    print('$' * i)
for j in range(5):  
    print('*' * j)
$
$$
$$$
$$$$

*
**
***
****
# what does this print?

for i in range(5):
    print('$' * i)
    for j in range(i):
        print('*' * j)      
$

$$

*
$$$

*
**
$$$$

*
**
***
# can use _ for loop variable when we don't need to reference it
for _ in range(10):
    print('Hello World!')
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!