This blog post demonstrates the use of lists and sets in Python. In this example, we will be using numeric values; however, Python is also capable of using strings within lists and sets.
Squared brackets indicate a list in Python. Below is a list with the name of "a".
a = [1,1,2,2,3,5,8,9]
The first position in a list has the index of 0.
So, if we code the following:
print("The first value in list a is ",a[0])
We will get the following:
The first value in list a is 1
If we want to add the first and last values in the list and print the sum, we would code the following:
sum = a[0] + a[7]
print("The sum of the first and last values in list a is ",sum)
The result of that code would be:
The sum of the first and last values in list a is 10
In addition to lists in Python, there are also sets. Sets are like lists, but they can only contain unique values. In list a, we can see that some of the values are repeated. If we make a set out of list a, the repeated values will be removed.
We make a set from list a and print the resulting set by coding the following:
b = set(a)
print("The set of values from list a is ",b)
The results of that code are as follows:
The set of values from list a is {1, 2, 3, 5, 8, 9}
Note that the {} brackets are indicating a set. Also note that the repetitive values have been removed to form a set of unique values.
Squared brackets indicate a list in Python. Below is a list with the name of "a".
a = [1,1,2,2,3,5,8,9]
The first position in a list has the index of 0.
So, if we code the following:
print("The first value in list a is ",a[0])
We will get the following:
The first value in list a is 1
If we want to add the first and last values in the list and print the sum, we would code the following:
sum = a[0] + a[7]
print("The sum of the first and last values in list a is ",sum)
The result of that code would be:
The sum of the first and last values in list a is 10
In addition to lists in Python, there are also sets. Sets are like lists, but they can only contain unique values. In list a, we can see that some of the values are repeated. If we make a set out of list a, the repeated values will be removed.
We make a set from list a and print the resulting set by coding the following:
b = set(a)
print("The set of values from list a is ",b)
The results of that code are as follows:
The set of values from list a is {1, 2, 3, 5, 8, 9}
Note that the {} brackets are indicating a set. Also note that the repetitive values have been removed to form a set of unique values.
Comments
Post a Comment