Hello Technotizers, in this article we will try to
give you detailed information on Python – Lists and their methods. Lists are
using to store many items in a single variable. They are among the 4 in-built
data types of Python that are used to store data, the other 3 being Tuples,
Sets and Dictionary.
Lists are created using square brackets:
city = ['Mumbai','Delhi','Chennai','Kolkata']
print(city)
The output is obtained
as:
['Mumbai', 'Delhi', 'Chennai', 'Kolkata']
Some points
to be remembered:
·
List items
are ordered, changeable and allow duplicate values.
·
List items
are indexed, the first item is indexed [0] and so on.
·
A list item
can be of any data type like int, string or Boolean. A list can also contain
items of mixed data types.
Examples:
All the
below given lists are valid in Python.
list2 = [1, 4, 24, 14, 8]
list3 = [True, False, False]
list4 = ["abc", 34, True, 40, "male"]
·
The list() constructor:
It is
another way of creating a list.
city = list(('Mumbai','Delhi','Chennai','Kolkata'))
So now let’s move forward!!
- Accessing list elements:
As seen in strings, list items are also
accessed in the same way as in strings. List items are indexed so they can be
accessed with the help of indexes. The indexing starts from 0 as usual.
Negative indexing means that the indexing begins from the end. -1 is the last
index, -2 the second last and so on. A range of indexes can also be specified
form where to start (inclusive) and where to end (exclusive).
city = ['Mumbai','Delhi','Chennai','Kolkata','Surat','Indore']
#referring index
print(city[2])
#negative indexing
print(city[-1])
#range of indexes
print(city[1:4])
#range of negative indexes
print(city[-3:-1])
The
output is obtained as:
Chennai
Indore
['Delhi', 'Chennai', 'Kolkata']
['Kolkata', 'Surat']
- Changing list elements:
Index number is referred to change the
value of an item. To change a range of specific items, a new list of values is
defined, and is referred to the range of indexes where we want to put the new
values.
#changing an item
city = ['Mumbai','Delhi','Chennai','Kolkata']
city[1] = 'Surat'
print(city)
#changing range of items
city = ['Mumbai','Delhi','Chennai','Kolkata']
city[1:3] = ['Surat','Indore']
print(city)
The
output is obtained as:
['Mumbai', 'Surat', 'Chennai', 'Kolkata']
['Mumbai', 'Surat', 'Indore', 'Kolkata']
If you
insert more items
than you replace, the new items will be inserted where you specified, and the
remaining items will move accordingly.
- Adding list elements:
To add an item at the end of the list, append()
method is used.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.append('Surat')
print(city)
#to store the item permanently in the
list
city = city.append('Surat')
The
output is obtained as:
['Mumbai', 'Delhi', 'Chennai', 'Kolkata', 'Surat']
To
insert an item at a specific index, insert() method is used.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.insert(1,'Surat')
print(city)
The
output is obtained as:
['Mumbai', 'Surat', 'Delhi', 'Chennai', 'Kolkata']
- Extend list:
The extend() method adds items from
another list to the existing list.
city1 = ['Mumbai','Delhi','Chennai','Kolkata']
city2 = ['Surat','Indore','Nagpur']
city1.extend(city2)
print(city1)
The
output is obtained as:
['Mumbai', 'Delhi', 'Chennai', 'Kolkata', 'Surat',
'Indore', 'Nagpur']
The extend()
method does not have
to append only lists, you can add any iterable object
(tuples, sets, dictionaries etc.).
- Remove list items:
The remove() method removes a specific
item.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.remove('Delhi')
print(city)
The
output is obtained as:
['Mumbai','Chennai', 'Kolkata']
The
pop() method removes a specified index. If the index is not specified then the
last item is removed.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.pop(1)
print(city)
#without specifying index
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.pop()
print(city)
The
output is obtained as:
['Mumbai', 'Chennai', 'Kolkata']
['Mumbai', 'Delhi', 'Chennai']
The
‘del’ keyword is also used to remove specified index. The ‘del’ keyword can
also entirely delete the list.
city = ['Mumbai','Delhi','Chennai','Kolkata']
del city[1]
print(city)
#delete entire list
del city
The
output is obtained as:
['Mumbai', 'Chennai', 'Kolkata']
The
clear() method clears the list. The list still exists but without any content.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.clear()
print(city)
The
output is obtained as:
[]
The
output shows that the list is now empty.
- Looping a list:
A for loop is used to loop through a
list. You can also loop through
the list items by referring to their index number. Use the range()
and len()
functions to create a suitable iterable.
city = ['Mumbai','Delhi','Chennai','Kolkata']
for i in city:
print(i,end=" ")
print('\n')
for i in range(len(city)):
print(city[i],end=" ")
The
output is obtained as:
Mumbai Delhi Chennai Kolkata
Mumbai Delhi Chennai Kolkata
The
len() method is used to get the length of a list.
To know more about for loops, refer the article Python - Loops
You can
loop through the list items by using a while
loop.
Use the len()
function
to determine the length of the list, then start at 0 and loop your way through
the list items by referring to their indexes. Remember to increase the index by
1 after each iteration.
city = ['Mumbai','Delhi','Chennai','Kolkata']
i = 0
while i<len(city):
print(city[i],end=" ")
i = i+1
The
output is obtained as:
Mumbai Delhi Chennai Kolkata
- Sort Lists:
The sort() method is used to sort the
list in ascending order by default. The lists that contain strings as items are
sorted in alphabetical order.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.sort()
print(city)
numbers = [12,98,5,7,25]
numbers.sort()
print(numbers)
The
output is obtained as:
['Chennai', 'Delhi', 'Kolkata', 'Mumbai']
[5, 7, 12, 25, 98]
To sort
the list in descending order, use the keyword argument reverse=True.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.sort(reverse=True)
print(city)
numbers = [12,98,5,7,25]
numbers.sort(reverse=True)
print(numbers)
The
output is obtained as:
['Mumbai', 'Kolkata', 'Delhi', 'Chennai']
[98, 25, 12, 7, 5]
You can
also customize your own function by using the keyword argument key =
function.
The function will return a number that will be used to sort the list (the
lowest number first).
def my_func(n):
return abs(n-50)
numbers = [100,65,50,45,80]
numbers.sort(key=my_func)
print(numbers)
The
output is obtained as:
[50, 45, 65, 80, 100]
The above code sorts the numbers based on how much close it is to number 50.
Note: By default the sort()
method is
case sensitive, resulting in all capital letters being sorted before lower case
letters.
To obtain the reverse of a list without
sorting, the reverse() method is used.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city.reverse()
print(city)
The
output is obtained as:
['Kolkata', 'Chennai', 'Delhi', 'Mumbai']
- Copy Lists:
The copy() method is used to copy one
list into another. Also the list() constructor is used to do so.
city = ['Mumbai','Delhi','Chennai','Kolkata']
city2 = city.copy()
print(city2)
numbers = [12,98,5,7,25]
numbers2 = numbers.copy()
print(numbers2)
The
output is obtained as:
['Mumbai', 'Delhi', 'Chennai', 'Kolkata']
[12, 98, 5, 7, 25]
- Join Lists:
One of
the easiest way to join lists is using the + operator. Another way to join two lists is by appending all the items from list2
into list1, one by one. Or you can use the extend()
method,
whose purpose is to add elements from one list to another list.
city = ['Mumbai','Delhi','Chennai','Kolkata']
numbers = [12,98,5,7,25]
#using + operator
print(city+numbers)
#using append() method
for i in numbers:
city.append(i)
print(city)
#using extend() method
city = ['Mumbai','Delhi','Chennai','Kolkata']
numbers = [12,98,5,7,25]
city.extend(numbers)
print(city)
The
output is obtained as:
['Mumbai', 'Delhi', 'Chennai', 'Kolkata', 12, 98, 5, 7, 25]
['Mumbai', 'Delhi', 'Chennai', 'Kolkata', 12, 98, 5, 7, 25]
['Mumbai', 'Delhi', 'Chennai', 'Kolkata', 12, 98, 5, 7, 25]
- List comprehension:
List comprehension offers a shorter
syntax when we need to create a mew list based on an existing list.
Let’s see an example:
Consider we want to create a list that
has names of cities that contain the letter ‘a’ in them, based on an existing
list. For this we write the code as:
city = ['Mumbai','Delhi','Chennai','Kolkata']
new = []
for i in city:
if "a" in i:
new.append(i)
print(new)
But
with list comprehension, all of this code can be done in one line.
city = ['Mumbai','Delhi','Chennai','Kolkata']
new = [i for i in city if "a" in i]
print(new)
Both
the codes give the same outputs as below.
['Mumbai','Chennai','Kolkata']
The
syntax for list comprehension:
newlist = [expression for item in iterable if condition == True]
Some
other examples:
city = ['Mumbai','Delhi','Chennai','Kolkata']
new = ['hello' for i in city]
print(new)
new = [i if i != "Mumbai" else "Surat" for i in city]
print(new)
new = [i for i in range(10) if i < 5]
print(new)
The
output is obtained as follows:
['hello', 'hello', 'hello', 'hello']
['Surat', 'Delhi', 'Chennai', 'Kolkata']
[0, 1, 2, 3, 4]
- List methods:
Python offers a bunch of list methods
given below:
Method |
Purpose |
Adds an
element at the end of the list |
|
Removes all
the elements from the list |
|
Returns a
copy of the list |
|
Returns
the number of elements with the specified value |
|
Add the
elements of a list (or any iterable), to the end of the current list |
|
Returns
the index of the first element with the specified value |
|
Adds an
element at the specified position |
|
Removes the
element at the specified position |
|
Removes
the item with the specified value |
|
Reverses
the order of the list |
|
Sorts the
list |
With this we come to an end of this article. Hope it was helpful. Do provide your feedback and ideas through comments, it would be highly appreciated. See you soon!
Keep coding and exploring new techs!!
0 comments:
Post a Comment