Python Lists

Python Lists: A list is a collection of ordered and changeable. In python, lists are written in square brackets. To some extent, lists are similar to arrays in C. The values stored in the list can be accessed by using slice operator ([] and [:]) with indexes starting at 0 at the beginning of the list and going their way to the end -1. A single list may contain DataTypes like Integers, Strings, as well as Objects. And the lists are also very useful for implementing stacks and queues. Lists are mutable, and hence, they can be altered even after their creation.



Example

thislist=["orange","blue","green"]
print(thislist)

Output
[‘orange’, ‘blue’, ‘green’]

Python Lists

Python Lists

Creating a List

The lists in python can be created by just placing the sequence inside the list. Like sets, the list does not need the built-in function for creation. And the list may contain duplicate values with their distinct positions. Sp duplicate values can be passed as a sequence at the time of list.

Example

# Python program to demonstrate 
# Creation of List 

# Creating a List 
List = [] 
print("Intial blank List: ") 
print(List) 

# Creating a List with 
# the use of a String 
List = ['Freshersnow'] 
print("\nList with the use of String: ") 
print(List) 

# Creating a List with 
# the use of multiple values 
List = ["freshers", "now"] 
print("\nList containing multiple values: ") 
print(List[0]) 
print(List[1]) 

# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Freshers', 'now'] , ['Freshers']] 
print("\nMulti-Dimensional List: ") 
print(List) 

# Creating a List with 
# the use of Numbers 
# (Having duplicate values) 
List = [1, 2, 4, 4, 3, 3, 3, 6, 5] 
print("\nList with the use of Numbers: ") 
print(List) 

# Creating a List with 
# mixed type of values 
# (Having numbers and strings) 
List = [1, 2, 'Freshers', 4, 'now', 6, 'Freshers'] 
print("\nList with the use of Mixed Values: ") 
print(List) 

Output

Initial blank List:
[]

List with the use of String:
[‘Freshersnow’]

List containing multiple values:
freshers
now

Multi-Dimensional List:
[[‘Freshers’, ‘now’], [‘Freshers’]]

List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:
[1, 2, ‘Freshers’, 4, ‘now’, 6, ‘Freshers’]

Access Items

You can access a list of items by referring to the index number. And the index must be an integer. A nested list is accessed using nested indexing.

Example: To print 2nd item in the list

# Python program to demonstrate 
# accessing of an element from the list 

# Creating a List with 
# the use of multiple values 
List = ["Freshers", "now"] 

# accessing a element from the 
# list using index number 
print("Accessing a element from the list") 
print(List[0]) 
print(List[1]) 

# Creating a Multi-Dimensional List 
# (By Nesting a list inside a List) 
List = [['Freshers', 'now'] , ['Freshers']] 

# accessing a element from the 
# Multi-Dimensional List using 
# index number 
print("Acessing a element from a Multi-Dimensional list") 
print(List[0][1]) 
print(List[1][0]) 


List = [1, 2, 'Freshers', 4, 'For', 6, 'now'] 

# accessing a element using 
# negative indexing 
print("Acessing element using negative indexing") 

# print the last element of list 
print(List[-1]) 

# print the third last element of list 
print(List[-3])

Output

List after Addition of Three elements:
[1, 2, 4]

List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple:
[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List:
[1, 2, 4, 1, 2, 3, (5, 6), [‘For’, ‘Freshers’]]

List after performing Insert Operation:
[1, 2, 4, 12, 1, 2, 3, (5, 6), [‘freshers’, ‘For’, ‘Freshers’]]

List after performing Extend Operation:
[1, 2, 4, 12, 1, 2, 3, (5, 6), [‘freshers’, ‘For’, ‘Freshers’], 8, ‘Freshers’, ‘Now’].

Changing Item value

If you want to change a specific item, referring to the index number.

Example

thislist=["orange","blue","green"] 
thislist[1]="violet"
print(thislist)

Output
[‘violet’, ‘blue’,’green’]

Loop through a List

You can also loop through the items by using a for a loop.

Example: print all the items in the list, one by one

thislist=["orange","blue","green"]
for x in thislist
print(x)

Output
orange
blue
green

Check if items in the list

To define if a specified item is present in the list.

Example: Check “if” blue is present in the list

thislist=["orange", "blue", "green"]
if "blue" in thislist: 
Print("yes,'blue' is in the list"]

Output
yes, ‘blue’ is in the list

Length of the list

To define how many items in the list() method.

 Example

thislist["orange","blue","green"]
print(len(thislist))

Output: 3 

Add Item to list

To add items to end of the list use append() method.

Example

thislist("orange","blue","green")
thislist.append("yellow")
print(thislist)

Output: [‘orange’, ‘blue’, ‘green’, ‘yellow’]

To add an item at the specified index, use insert( ) method:

Example

thislist=["orange","blue","green"]
thislist.insert(1,"pink")
print(thislist)

Output: [‘orange’, ‘pink’, ‘green’, ‘yellow’]

Remove Item

There are several methods to removes as follows:

Example

thislist=["orange","blue","green"]
thislist.remove("orange")
print(thislist)

Output
[‘blue’,’green’]

pop( )

It is an inbuilt function in Python. It removes and returns the last value from the list or the given index value.

Syntax: list_name.pop(index)

Example

thislist=["orange","blue","green"]
thislist.pop( )
print(thislist)

Output
[‘blue’, ‘green’]

Delete( )

This delete() method deletes all the elements in range starting from index.

Example

# initializing list 
lis = [1, 2, 7, 5, 4, 7, 8] 
# using del to delete elements from pos. 2 to 5 
# deletes 3,5,4 
del lis[2 : 5] 
# displaying list after deleting 
print ("List elements after deleting are : ", end="") 
for i in range(0, len(lis)): 
  print(lis[i], end=" ") 
print("\r") 
# using pop() to delete element at pos 2 
# deletes 3 
lis.pop(2) 
# displaying list after popping 
print ("List elements after popping are : ", end="") 
for i in range(0, len(lis)): 
  print(lis[i], end=" ")

Output

List elements after deleting are: 1 2 7 8

List elements after popping are: 1 2 8

List() Constructor

A constructor is an instance method that usually has the same name as a class name, and can be used to set the values of the members of an object, either to default or to user-defined values. A constructor is a special method of class or structure in object-oriented programming that initializes an object of that type.

Example: use the list() constructor to make a list

thislist=list(("red","green","blue"))
print(thislist)

Output: [‘red’,’green’, ‘blue’]

Slicing of a list

In Python lists, we are having multiple ways to print the whole list with all the elements. In case if you want to print a specific range of elements from the list we should use the slice operation(:).

Example

# Creating a List 
List = ['F','R','E','S','H','E', 
    'R','S','N','O','W'] 
print("Intial List: ") 
print(List) 

# Print elements of a range 
# using Slice operation 
Sliced_List = List[3:8] 
print("\nSlicing elements in a range 3-8: ") 
print(Sliced_List) 

# Print elements from beginning 
# to a pre-defined point using Slice 
Sliced_List = List[:-6] 
print("\nElements sliced till 6th element from last: ") 
print(Sliced_List) 

# Print elements from a 
# pre-defined point to end 
Sliced_List = List[5:] 
print("\nElements sliced from 5th "
  "element till the end: ") 
print(Sliced_List) 

# Printing elements from 
# beginning till end 
Sliced_List = List[:] 
print("\nPrinting all elements using slice operation: ") 
print(Sliced_List) 

# Printing elements in reverse 
# using Slice operation 
Sliced_List = List[::-1] 
print("\nPrinting List in reverse: ") 
print(Sliced_List)

Output

Intial List:
[‘F’, ‘R’, ‘E’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’, ‘N’, ‘O’, ‘W’]
Slicing elements in a range 3-8:
[‘S’, ‘H’, ‘E’, ‘R’, ‘S’]
Elements sliced till 6th element from last:
[‘F’, ‘R’, ‘E’, ‘S’, ‘H’]
Elements sliced from 5th element till the end:
[‘E’, ‘R’, ‘S’, ‘N’, ‘O’, ‘W’]
Printing all elements using slice operation:
[‘F’, ‘R’, ‘E’, ‘S’, ‘H’, ‘E’, ‘R’, ‘S’, ‘N’, ‘O’, ‘W’]
Printing List in reverse:
[‘W’, ‘O’, ‘N’, ‘S’, ‘R’, ‘E’, ‘H’, ‘S’, ‘E’, ‘R’, ‘F’]

Python List Methods

A method, in the context of object-oriented programming, is a procedure or a function in the class. As a part of the class, a method defines the behavior of class instance. A class can have more than one method.

Python has a set of built-in methods that can be used on lists.

Method Description
append( ) Adds an element at the end of the list
clear( ) Removes all the elements from the list
copy( ) Returns a copy of the list
count( ) Returns the number of elements with a specified value
extend( ) Add the elements of a list, to the end of the current list
index( ) Returns the index of the first element with specified values
insert Adds an element at the specified position
pop( ) Removes element at the specified position
remove( ) Removes the item with a specified value
reverse( ) Reverse the order of the list
sort( ) sorts the list

Built-in Functions with List

Function Description
round( ) Rounds off to the given number of digits and returns the floating point number
reduce( ) apply a particular function passed in its argument to all of the list elements stores the intermediate result and only returns the final summation value
sum( ) Sums up the numbers in the list
ord( ) Returns an integer representing the Unicode code point of the given Unicode character
cmp( ) This function returns 1 if the first list is “greater” than the second list
max( ) return maximum element of a given list
min( ) return minimum element of a given list
all( ) Returns true if all elements are true or if a list is empty
any( ) return true if any element of the list is true. if the list is empty, return false
len( ) Returns length of the list or size of the list
enumerate( ) Returns enumerate object of the list
accumulate( ) apply a particular function passed in its argument to all of the list elements returns a list containing the intermediate results
filter( ) tests if each element of a list true or not
map( ) returns a list of the results after applying the given function to each item of a given iterable
lambda( ) This function can have any number of arguments but only one expression, which is evaluated and returned