what is list in Python and it’s operations?
Definition of List:
A collection of values, or elements, that can have any data type is commonly known as Python list. A list is presented with square brackets [], in which the values are separated by commas.
For example;
a = [7, ‘rain', 5, 'frog', 4]
Negative indexing:
The first element in the list hold index 0, the position of first element starts with zero-indexing, where the second element has index 1, and go on.
Lists can be so long so that to reach the last element is the lists we can use negative indexing in which we count the elements from backward. The last element of the list has index -1, the second to last has index -2, and go on.
To select the last element "p' from the below mentioned list x , place -1 in square bracket. The element has index -1, as it is the last element of the lists.
e.g.
x = ['b', 'd', 'm', 'p']
print(x[-1])
print(x[-4])
Result:
p
b
Indexing and slicing:
For accessing the element in the Python lists we use index, as we know that the first element is placed at index 0, and the second element is placed at index 1, and go on. To pick the first element ‘d’ in the below mentioned list we insert 0 in square brackets. The element has index 0 since it is the first element.
e.g.
g = [a', 'b', 'c']
print(g[0])
print(g[1])
Result:
d
f
Further, multiple elements can be selected from a list with the help of slicing. For slicing the list, we have to specify a range using a colon and the format [start: end]. The start index is included in the selection, where as the end index is excluded. The result is in a form of new list of the selected elements.
e.g.
x = ['a', 'b' , 'c', 'd', 'e']
print(x[2:4])
Result:
[‘c’, ‘d’]
For slicing from the first element or to the last element, you do not required to include the index.
For example;
f = ['a', 'b', 'c', 'd', 'e']
print(f[:3])
print(f[2: ])
Result:
['a', 'b', 'c']
['c', 'd', 'e']
List of lists:
Any type of data can be saved in list, and other list can also be made where mixed data can be simplified is the form of new list that is called it’s sub list.
a = ["Netherlands", "Europe"]
b = ["Saudia", "Asia"]
c = ["Nigeria", "Africa"]
countries = [a, b, c]
print(countries)
Result:
[["Netherlands", "Europe"], ["Saudia", "Asia"], ["Nigeria","Africa"]]
Referencing and copying:
When we use =sign it creates a reference for first list and does mean copying. Means that whenever you make changes to the initial list, the change effect the new list as well.
x = [6, 7, 8]
y = x
x[1] = 4
print(y)
Output:
[6, 4, 8]
For creating a separate copy of any list, you have to slice it [:] or put it inside the list() function. In the following lists you can compare that y and z, are remain unchanged by the alteration made to x, as they were copied before the alterations.
x = [2, 3]
y = x[ : ]
z = list(x)
x[0] = 1
Print(x, y, z)
Output:
[1, 2], [2, 3], [2, 3]
Comments
Post a Comment