Python Lists

Python Lists:

Python list is a collection or an array which is used to store various types of data.

Syntax:

<list_name>=[value1,value2,value3,…,valuen]

Features of Python Lists:

  • They are ordered and changeable.
  • They are written within square brackets.
  • They can store multiple types of data.
  • They are mutable. Thus, modify the current list only for any changes in the list.
  • Python Lists supports various operations.
  • The elements of a python list are separated by commas and starts with index 0.

Python Lists Methods:

METHODS USES
append() To add an element at the end of the list.
clear() To remove all the elements from the list.
cmp() To compare two lists.
copy() To return a copy of the list.
count() To return the number of elements with the specified value.
extend() To add the elements of a list to the end of the current list.
index() To return the index of the first element with the specified value.
insert() To add an element at the specified position.
len() To get the number of elements in a list.
list() To convert a sequence type to a list.
min() To get the minimum value from the list.
max() To get the maximum value from the list.
pop() To remove an element at the specified position.
remove() To remove the first item with the specified value.
 reverse() To reverse the order of the list.
sort() To sort the list.

Python Lists Operators:

OPERATORS SYMBOLS USES
Concatenation + To add two lists.
Replication * To repeat the list a specific number of times.
Slicing [i:j] To get a sub-list of specified start and end index.
Deleting del To delete an element from the list.

Example:

a =  ["python", "java", "php", "HTML", "javascript", "CSS", "Bootstrap"]
print "\n"
print "List is:"
print a
print "\n"
 
print "Get the element at position 0."
print(a[0])
print "\n"
 
print "Get the elements from position 1 to position 4."
print(a[1:4])
print "\n"
 
print "Remove php from the list."
a.remove("php")
print a
print "\n"
 
print "Get the total length."
print(len(a))
print "\n"
 
print "Remove the last index."
a.pop()
print a
print "\n"
 
print "Delete the 3rd element."
del a[3]
print a
print "\n"
 
print "Replace the 2nd element."
a[2] = "jQuery"
print a
print "\n"

Output: