Lists - Ipynb - Colaboratory
Lists - Ipynb - Colaboratory
Code Text
The list is a data structure in Python which acts as a container to hold or store multiple data at the same time. Lists are mutable or changeable
and ordered sequence of elements. To know more about Python Lists you can visit the official Python Lists documentation. One thing you have
to keep in mind is that often we must declare lists using [ ] brackets. The elements inside the [ ] are the values of the list. For example:
[1, 2, 3, 4, 5]
Here the name of the list is "num" and the list values are 1, 2, 3, 4, 5. The advantages of lists are the values inside the lists need not be of the
same type meaning:
# Adding the values irrespective of their data type: Integer, String, float.
num = [1, 2, 3, "Tanu", 4.0, 4/2]
num
In order to check the variable if it is a list or not, use the "type" method as follows:
list
Let us create a list called "name" and then insert some values, later we can then access the elements inside the list using the index with the
help of [ ] by placing the index values inside it. We can then calculate the length of the list by using the len ( ) method, just pass the name of the
list as an argument to the len( ) method, finally we can also get the length of the individual elements inside the list by using the same len ( )
method but this time we should specify the index position as an argument.
'Tanu'
# Calculating the length of the list.
len(name)
Assignment with a "=" on lists does not make a copy. Instead, the assignment makes the two variables point to the one list in the memory.
Sometimes an assignment operator can be used to copy from one list to the other.
[]
Usually appending two lists can be done by using append( ) method, but appending can also be done by using a '+' (here + doesn't mean
addition) whereas + can be used to add or merge two lists into a single list as shown below.
In Python the "for" and "in" are called constructs, these constructs are easy to use, they are used whenever you need to iterate over a list.
# Creating a list
num = [1, 2, 3, 4, 5]
# Assigning sum to 0
sum = 0
# Using a for loop to iterate over the list
for i in num:
sum = sum + i
print(sum) # 15
15
The "if " and "in" construct on its own is an easy way to test if an element appears in a list (or other collection), it tests if the value is in the
collection, returning True/False. This also works for the string, characters in Python.
# Creating a list
num = [1, 2, 3, 4, 5]
if 1 in num:
print("True")
else:
print("False")
True
The Range function in Python is used as a boundary in the looping constructs, the range function starts from 0 to n-1, it doesn't include the last
number as shown below.
0
1
2
3
4
Python has a standard while-loop which works similar to the For loop, first you have to initialize, then insert a condition and finally increment
# Initialisin i to 0
i = 0
while i < 10:
print(i) # 0–9
i = i+ 1
0
1
2
3
4
5
6
7
8
9
8) List methods.
Below are some of the most common list methods shown with an example.
The list.append( ) just appends an element to the list but never returns anything, it just appends the element to the existing list.
# Creating a new list called name
name = ['Tanu', 'Nanda']
# Before appending
name
['Tanu', 'Nanda']
# Using the append operation on the current ("Prabhu") is the value to be appended.
name.append("Prabhu")
# After appending
name
List.insert( ) operation is used to insert the elements inside a list with a specified index position.
['Tanu', 'Nanda']
The extend method adds the elements to the end of the new list. It is similar to append but you have to pass the list as an argument whereas in
append it's not necessarily true.
['Tanu', 'Nanda']
# Using extend but make sure that you put the elements in a []
# Without []
name.extend("Prabhu")
# After extending
name
# After []
name.extend(["Prabhu"])
name
The index operation in list searches the element in the list and then returns the index of that element. If the element is not present in the list
then the index method returns a value error telling that the element is not in the list.
['Tanu', 'Nanda']
# After indexing, type the element that you want to index.
name.index("Nanda")
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-28-e4d303e9b027> in <module>()
----> 1 name.index("Mercedes")
The Remove method in lists searches for the element and then on matching removes the element present in the list. Also throws an error when
the element is not in the list.
['Tanu', 'Nanda']
# After removing
name.remove("Nanda")
name
['Tanu']
name.remove('Prabhu')
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-31-0cd347413bd4> in <module>()
----> 1 name.remove('Prabhu')
As the name suggests the sort method sort the elements in ascending order. This method doesn't return anything.
[1, 4, 5, 2, 3]
# After sorting
num.sort()
num
[1, 2, 3, 4, 5]
As the name suggests the reverse method reverses the entire list. This method doesn't return anything.
num.reverse()
# After the reverse
num
[5, 4, 3, 2, 1]
The Pop method removes and returns the element at the given index. Returns the rightmost element if the index is omitted (roughly the
opposite of append( )).
[1, 2, 3, 4, 5]
# After popping
num.pop(1)
num
[1, 3, 4, 5]
9) List Slices
Slicing the list means cutting down the list elements, it and can also be used to change sub-parts of the list.
This is the most important technique, often we need to convert the string to a list in our projects, this is an easy approach that does the job for
us. This below example was referred from geeksforgeeks.com. Here we are using the split method from the strings where the split method just
splits the elements from the string and then broadcasts into a list as shown below.
# Creating a String
String = "Tanu"
String
'Tanu'
str
['Tanu']
type(name)
list
Hence above are the very important techniques or methods of Lists in Python. Most of the examples were referred from Python Lists from
Google. I have written this in a simple way such that everybody can understand and master the concepts of lists in Python. If you guys have
some doubts in the code, the comment section is all yours.
ThankYou.