Module 2: working with strings, lists, tuples, dictionaries Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

working with strings - talk about index, slicing, string operators, and formatting

A

A sequence of characters enclosed with a single or double quote
You can think of strings as a collection of individual characters

Index/slicing:
Len(message) will give you the length of the string
Print (message[0]) will give you the first character of message
A slice is a segment of a string beginning with a start index and continuing up to but not including an end index
S1[2:6] gives you characters from 2-6
Message[6:] would give you the fifth character until the end, you can do the same thing to get the begginig up to a certain character
[:] selects everything
[2:] selects everything from index two to the end
[:2} everything before the second element
You can also select specific elements like [0:2:5] you are selecting these ones

Count/find methods:
Print(message.count(‘l”)) – would count all the l’s in a message
Print(message.find(‘l”)) – would find all the l’s in a message

2.2.3 String Operators
You can use + to concatenate two strings
“abc123” + “def456’ returns “abc123def456”
You can multiply str * int
You cannot multiply str with a str
Print (dir(str)) will print all of the functions that can be used for strings
Then to learn more about a function you do help(str.function name)

String formatting:
Is preferred over concatenations when you’re dealing with longer more complex strings
Message = f“{greeting}, {name},Welcome!”.
What you’re dealing here is creating two placeholders and then giving them a value greeting and name which should have been assigned in your variable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

working with strings, define, formatting, and different ways of working with them

A

Similar to a string, a list is a sequence of values rather than characters
The values are called elements or items
Lists are in square brackets []
Working with lists is similar to strings like len can also be used
A string can be changed into a list with the split method

my_list = [11, 22, 33, 44, 55]
len(my_list)
my_list[0]
# if you want the last element you can do [-1] or [-2] for the second last one

Lists can work with a range of datatypes, are changeable, and versatile (append, extend, insert, remove, sort). The only time you might want to work with strings are if you have textual data and you want it to be unchanged.

.append = add an item at the end of the list
My_list.append(2)

.insert = add an item at a specific location in the list
My_list.instert(location, then value)
My_list.insert(0, “Kobe”)

.extend = when you have multiple values you want to add to the list
Adding a list to another list
My_list.extend(my_list2)

.remove = remove and individual value
My_list.remove(“Kobe”)

.pop = remove the last value of the list
My_list.pop

.reverse = reverse your list
My_list.reverse()

.sort = sorting the list in alphabetical order or ascending order for numbers /
My_list.sort
For ascending you still need to put in the argument (reverse=False)
For descending order you can do my_list.sort(reverse=True)
This won’t change the original list so you actually have to create a new variable
Sorted_list = sorted(my_list)

.index = finding a value in the list
Print(my_list.index(“Kobe”) – will return what place it’s located
You can also do print(“Kobe” in my_list) – will return true or false if it’s in the list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

what are tuples

A

Don’t need to use as much compared to a list because basically same thing but is immutable. The reason why you might need a tuple is because sometimes you have a list that is based on another list – in this case any modifications to the second list might change the initial list. Instead you can have the first list as a tuple so that any changes to list 2 will not result in list 1 being changed.

Similar to lists but are immutable
New_tuple: is created from a comma-seperated sequence of strings
Vowels: is created by splitting a string

new_tuple = “apple”, “banana”, “orange”
new_tuple

output:
(‘apple’, ‘banana’, ‘orange’)

Because they are immutable you don’t have a lot of options that a list has like appending, because it mutates the tuples.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

what are dictionaries

A

Similar to a list except the indices are not limited to only integers
A set of key-value pairs where the key is index to its associated value
Called dictionary because it’s like you have a definition for every word, for every key you have a value
Done with {}

{key_1: value_1, key_2: value_2, …}

They are mainly used to look up values
Below, we create a key and an associated value
Then we print the dictionary
And we list only values
To look up elements you have to search them using the key name

Student = {‘name’: ‘John’, ‘Age’: 25, ‘courses’: [‘Math’, ‘CompSci’]}
Print(student) – brings back entire dictionary
Print(student[‘courses’])

The dictionary can hold any data format

.get method returns a value for the key you pass
Print(student.get(‘name’))

You can also add new key value pairs to the dictionary
Student[‘phone’] = ‘555-5555’

.update method lets you update several key value pairs at the same time
Student.update({‘name’: ‘Jane’, ‘phone’: ‘555-5555’})
This also creates the new key-value pair for phone
Del method allows you delete a key value pair
Del student[‘age’]

Print(len(student))

Print(student.keys()))
Print(student.values()))
Print(student.items()))

To loop through your dictionary you will need to write it differently than lists because you have key and values
For item in student.items():
Print(item)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly