Chapter 7-
List
Lists
You can make lists of objects from the data types you’ve learned about so far. A list is also considered a data type.
Lists are indicated by brackets and you can separate list elements with commas:
[1,5,6,4,8]
["hi", "hello", "hey"]
["hi", 5, "hello", 8,"hey"]
Notice that the output for each list object is the list itself.
List Operations
You can perform operations on lists. Take note of what happens when you use the addition operator.
[1,2,3] + [4,5,6]
a = [1,2,3]
b = [4,5,6]
c = a+b
c
a+[4,5,6]
List Methods
You can add and remove single elements from lists. Here we start with an empty directory and add and remove items.
a = [ ]
a.append("Hey")
a.append("Hi")
a
a.remove("Hey")
a
A method is a function that belongs to a specific object type. In this
case, the append and remove methods can generally be applied to list objects. These two methods modify list a.
Indexing
You can access elements in a list by referencing the index of the element.
a = ["Hi","Hello","Hey","Howdy"]
“Hi” is in index 0.
“Hello” is in index 1.
“Hey” is in index 2.
“Howdy” is in index 3, and so on.
Compare the following. Notice that the ‘#’ begins the comment section of each line and will not show in your output.
a[0] # first element of list a
a[0:1] # index 0 through 1, not including 1
a[0:2] # index 0 through 2, not including 2
a[:2] # up to index 2, not including 2
a[1:3] # index 1 through 3, not including 3
a[-1] # last element of list a
a[-3:-1] # start at 3rd from end, not including last
a[-3:] # start at 3rd from end, including last
Note that the datatype of a[0] is an integer while the datatype of a[0:1] is a list.
You can find the index of the first occurrence of an element using the index method.
a = [1,2,3,8,8]
a.index(8)
Exercise 2
Create any list b. Use indexing to define a list c that contains only the last two elements of list b.
Nested Lists
Since a list is also considered a data type, you can create lists of files, with each list object as an element of the outer list.
[ [1,2,3], [4,5,6], [7,8,9] ]
a = [1,2,3]
b = [4,5,6]
c = [7,8,9]
d = [a,b,c]
d
You can access the first element in list b from list d through indexing.
Start by indexing list d to find the second element of list d to access list b.
d[1] # the same as list b
Then index list b to find the first element of list b.
d[1][0]
Exercise 3
Access the second element in list a from list d.
String Indexing
String indexing works similarly to list indexing.
a = "Hello, how are you?"
a[0]
a[0:5]
a[0:5] + a[-5:]
Exercise 4
a = ["hi","hello","hey","howdy"]
Using list indexing, create a string b that combines the first two letters of each string element in list a.
If Statements and For Loops
If Statements
An if statement is used to run commands only when conditions are met. The colon and indentation are necessary to indicate what to run when the indicated output from the Boolean operation is True.
a = 2
b = 4
if a == b:
print(a)
You won’t be able to run the if line by itself. You will need to run the entire block together by running the indented lines of code with the if statement. You can do this by highlighting both lines and using Run selection.
Notice here that the print statement above does not get run and therefore there is no output.
Exercise 1
Modify the code above so that the if condition is met and the output gives us a.
Use else to state which command should run when the condition is not met. You will need the run the entire block of code below together using Run selection.
if a == b:
print(a)
else:
print("Not equal")
Exercise 2
a = 1
b = 2
c = 3
if a > b:
a = a + b
print(a)
else:
print(b)
print(a)
Determine what the output will be if you run the lines above.
In some cases, you want to check multiple alternative conditions. For this, you use elif. It allows you to create one or more alternative conditions to the if condition.
When the if condition is met, only the commands under the if statement will run. When the if condition is not met but the elif condition is met, only the commands under the elif statement will run. When neither the if condition nor the elif conditions are met, only the commands under the else statement are run. Run the following block of code together.
if a == b:
print(a+b)
elif a < b:
print(a)
else:
print(b)
For Loops
For loops are used to perform the same commands on a list’s elements. Just as with if statements, you will need to run everything indented under the for statement along with the for statement.
Run the following for loops:
a = [1,2,3,4,5,6]
for i in a:
print(i)
for i in a:
print(i + 2)
Exercise 3
Create a for loop that prints only the first 3 elements of list a above. Hint: Use list indexing.
You can combine if statements and for loops to pick out and run commands on select elements in a list.
for i in a:
if i > 2:
print(i)
b = [4,5]
for i in a:
if i not in b:
print(i)
Exercise 4
a = [1,2,3,"Hello",4,5,"Hi",6]
Use a for loop and if statement to print out only the strings in list a. Hint: You will need to use a Boolean operator to check the object types of each element.
Exercise 5
Create an empty list b. Use a for loop and if statement to add all string elements in list a above to list b. Hint: Use a list operation.
Exercise 6
Add one line to the output from Exercise 5 to also remove all string elements from list a.
Dictionaries
With dictionaries, you can reference data based on a key rather than an integer as you would in a list. A dictionary element is organized as a key-value pair that is separated by a colon. Pair elements are separated by commas.
pets = {'cat': 'feline', 'dog': 'canine'}
Take a look at the keys and values in the pets dictionary.
pets.keys()
pets.values()
Unlike a list, a dictionary is unordered or does not use numbers for indexing. Instead, the key is used to find an associated value.
pets['cat']
Dictionaries are statistics sorts inside the Python programming language that is much just like a listing of sure gadgets contained in a selected collection. Let us project into some of the similar characteristics and variations that lists and dictionaries share, which will get the basic concept of what dictionaries are all approximately. Same traits of those two information types include: They are both mutable, for this reason because of any moving at any unique moment of time, they're dynamic. They are able to change in a manner that they're to grow and shrink for the duration of any episodes and a dictionary is able to containing any other dictionary in it, and a list is too ready to incorporate some other list in it consequently concluding that those statistics types may be nested. The only difference between those two facts types comes from how the information values are accessed. Lists are typically obtained with the aid of numerous indexing operations while dictionaries are primarily accessed with the assistance of the use of multiple sorts of keys.
Dictionaries basically consist of a few key-price pairs that usually are the vital thing to a targeted associated fee. We outline a dictionary in Python with the aid of first enclosing the whole listing the usage of curly brackets, setting a complete colon that separates the critical thing pairs to the associated value located, and lastly with the aid of the usage of a comma mark in isolating the numerous styles of key
pairs which might be available in the dictionary. Another manner in which dictionaries may be constructed inside the Python world is through the use of dict() feature within the program. This one works in a way that the price of the argument inside the dict() feature includes the keys and the respective values which have been paired in conjunction with it. Kindly recollect that square brackets are commonly used to comprise the key-price pairs inside the application in question. Once dictionaries have been described, it's far viable to display its contents where they get displayed simply the identical manner they were described in a structural way.
Dictionaries are accessed via specifying its relevant key inside rectangular brackets symbol, and in a case wherein a certain key does now not exist
in a particular dictionary, an exception is raised right away as an error made. It is then possible to feature an individual entry in a specific dictionary in which a brand new key with its price is assigned in the software. In updating a selected access, an original cost is just attached to an existing key. During the delete of an entry operation, a del assertion is usually used specifying the real key to delete.
Lastly, strategies and diverse operations are usually applied in dictionaries so various tasks may be achieved. For example, if a developer has the purpose of copying a particular dictionary, he or she is obligated to apply the copy() method of the Python programming language.
Some of the opposite strategies include:
¾ Clear method - this method clears all of the forms of elements which can be present in the dictionary.
¾ Get approach - this one offers the fee of the key that has been certain within the dictionary.
¾ From keys - this kind of method gives out a specific quantity of keys and values from the dictionary.
¾ Keys - outputs a list that entails the keys in the dictionary.
¾ Pop - this technique eliminates the elements with the required keys. Value approach – this approach gives out a collection of all the values which can be present in a positive dictionary.