List in Python


Below script covers the use of data structure  List in Python.

For understanding the code ,I have provided comments along with code and the output below it.

Kindly provide comments to improve the article.

##########################################################
## Basics of DATA STRUCTURE  `LIST`  in python
## output of all the commands is given after every command
##########################################################

#!/bin/python3
import os
import sys
blank_list = [] #definition of blank list
letters = [‘a’,’b’,’c’,’d’] #definition of list with data in it .
print(letters)
”’
[‘a’,’b’,’c’,’d’]
”’
#Method1: Printing directly from list
for letter in letters:
print(letter)
#Method2: Calculate the length of the list and iterate through the list using range method
list_len = len(letters)
for i in range(list_len):
print(letters[i])
#Appending data to a list
letters.append(‘e’)
print(letters)
”’
[‘a’,’b’,’c’,’d’,’e’]
”’
#Extend the list by appending a list
numbers = [1,2,3,4]
letters.extend(numbers)
print(letters)
”’
[‘a’,’b’,’c’,’d’,’e’,1,2,3,4]
”’
#insert an item for a given position
i = 4 #here 4 would mean postion 5 in the list ,as index starts from 0
letters.insert(i,’f’)
print(letters)
”’
[‘a’,’b’,’c’,’d’,’f’,’e’,1,2,3,4]
”’
#remove an item from list
letters.remove(‘a’) #if there are multiple ‘a’ then it would remove the first a.#if the item is not there it would give an error.
print(letters)
”’
[‘b’,’c’,’d’,’f’,’e’,1,2,3,4]
”’
#remove an item from a given position
letters.pop(2) #as index starts from 0 , 2 would refer to third position .
# if no position is given it will remove the last item
#if the postion given is out of range it will give an error.
print(letters)
”’
[‘b’,’c’,’f’,’e’,1,2,3,4]
”’
#return the position of an item in list
print(letters.index(1)) #if there is no such item it will give an error.
”’
4
”’
#count the number of an item in the list
print(letters.count(‘c’))
”’
1
”’
#reverse a list
letters.reverse()
print(letters)
”’
[4, 3, 2, 1, ‘e’, ‘f’, ‘c’, ‘b’]
”’
#sort the items in a list in ascending order
letters.sort()
print(letters)
”’
[1, 2, 3, 4, ‘b’, ‘c’, ‘e’, ‘f’
”’
#sort the items in a list in descending order
letters.sort(reverse=True)
print(letters)
”’
[‘f’, ‘e’, ‘c’, ‘b’, 4, 3, 2, 1]
”’

Comments

Popular posts from this blog

Best Phones under ₹25000 to buy in September2021

Best Phones under ₹25000 to buy in 2022

Best Phones under Rs.50000 in August 2021