Python Lists

list is basic data type in python programming. that are used to store single and multiple data. this data may as similar or different. This element are stored within the ([]) subscript operator. and multiple element are separated by comma (,). there syntax as follows.

 list_variable=[data-1,data-2,...,data-N]
key point Overview
list_variable This is list variable name
data Value of list element
comma (,) Used to separate elements

list element are internally use key and value pair. this key is also know as index. this is depends on sequence of element.For example

#defined list iteams
color=['red','blue','green','yellow','pink']
#display all element of list
print(color)

#display zero index value
print("color[0]",color[0])
#display 2 index value
print("color[2]",color[2])
#display -2 index value
print("color[-2]",color[-2])
Output
['red', 'blue', 'green', 'yellow', 'pink']
('color[0]', 'red')
('color[2]', 'green')
('color[-2]', 'yellow')

In this example list are contain 5 element. In given below image are mentioned value and index of every data value.

Python list values & index

list index is start by zero form left to right are increment index by one and access the list element by using of particular specified index. In similar way from right to left list index are start with -1 and decrement by one. this is very interesting and useful features. and list are capable to store different type of data. see example.

#defined list collection of items
collection=[1,11.11,"Code"]
#display all element of list
print(collection)
#display type value
print(type(collection[0])) #integer value
print(type(collection[1])) #float value
print(type(collection[2])) #string value
Output
[1, 11.11, 'Code']
<type 'int'>
<type 'float'>
<type 'str'>

Note that given example list are contain three different data value. this value are access by its index . and help of type() function are display its data type.

Base index of list is start 0 value. confusion can arising in your minds when working of negative index. so its very important to understand how to nagative index will work. look at one example.

#     index 0   1   2   3   4   5 [left to right]
collection=[10, 20, 30, 40, 50, 60]
#    index  -6  -5  -4  -3  -2  -1 [right to left]

In this program list are total six element. Of access this list element using negative index then use this formula.

 listVariable[ totalElement (length) + (nagative index)]

Assume that in previously example try to use index element -1. see example.

#     index 0   1   2   3   4   5 [left to right]
collection=[10, 20, 30, 40, 50, 60]
#    index  -6  -5  -4  -3  -2  -1 [right to left]

# Negative index  formula(length=6)     equal to positive
# collection[-1] = collection[6 + (-1)] = collection[5]
print(collection[-1]) 
Output
60

In this example get the value of collection[-1] are equivalent to collection[6+ (-1)] in list. Here 6 is length of list and -1 is negative index. so result is collection[6+(-1] is equal to collection[5] in list. similar way are get other negative index value.

what happens when given -0 for list index. that are equivalent to 0 (zero). see example

#     index 0   1   2   3   4   5 [left to right]
collection=[10, 20, 30, 40, 50, 60]
#    index  -6  -5  -4  -3  -2  -1 [right to left]

print(collection[-0]) 
Output
10

Slicing in list element

Slicing is a way to use small piece of portion in of given list. that are very useful to perform operation of list. for example assume that list are contain 1000 of element but we are only need to small portion of this list. then we can used this methods. Access list element portion using this syntax.

variableList[startIndex : endIndex]

for example

# list elements
collection=[10, 20, 30, 40, 50, 60]

#display element of index 1 to 3
print(collection[1:4]) 

#create new list using of collection list
#use element 1-3
info=collection[1:4]

#display new list elements
print(info) 
Output
[20, 30, 40]
[20, 30, 40]

In this program prints a list element between specified ranges. In here 1 is used starting index and 4 is used to ending index. and between them use in (:) colon operator. so this program are create two different lists. see this image.

python list slicing

so what going on in this program. there are collection list are contain 6 elements. there is display few element in between the list and also making a new list. this new list are start with the index of zero. and there is 3 elements. so collection[1:4] are returning a list which are contains 3 element. and note that collection[4] are not included in second list.

Negative value can be used to split portion of list. for example.

# list elements
items=[11,22,33,44,55,66,77,88]

#display element of index 3-4
# items[3],items[4]
print(items[-5:-3]) 

# empty list
print(items[0:-0])

#display element 0-7
print(items[0:-1])

#display element 6-7
print(items[-3:-1])


# empty list
print(items[-1:3])
[44, 55]
[]
[11, 22, 33, 44, 55, 66, 77]
[66, 77]
[]

Note that first index are smaller than second index this is valid condition to retrieve element of list. otherwise it will return empty list.

Few interesting point when not provide first starting index value then interpreter are assume that is zero, and not given the ending index then its will assume that the last index(length of list) of given list and using last element as well. for example.

# list elements
temp=['A','B','C','D']
#not provide first index
print(temp[:3])
#not providing last index
print(temp[0:])
output
['A', 'B', 'C']
['A', 'B', 'C', 'D']

Add list items

There are various way to add list item in python.

# defined lists elements

first=['A','B','C']

second=[1,2,3,4]

third=["c","c++"]

fourth=[1]

print("Before Added item List is")

print("first list  :",first)
print("second list :",second)
print("third list  :",third)
print("fouth list  :",fourth)

#Add list items

#Method 1 concatenation using (+)
first=first + ['D','E','alphabet']

#Method 2 using append function
second.append('number')

#Method 3 using insert function
third.insert(1,'Python')

#Method 4 using extend function
fourth.extend(["OK"])

print("After Added item List is")

print("first list  :",first)
print("second list :",second)
print("third list  :",third)
print("fouth list  :",fourth)

Output
Before Added item List is
('first list  :', ['A', 'B', 'C'])
('second list :', [1, 2, 3, 4])
('third list  :', ['c', 'c++'])
('fouth list  :', [1])
After Added item List is
('first list  :', ['A', 'B', 'C', 'D', 'E', 'alphabet'])
('second list :', [1, 2, 3, 4, 'number'])
('third list  :', ['c', 'Python', 'c++'])
('fouth list  :', [1, 'OK'])

In this program given four different techniques to add list item. before explain how it will work. first look at view initial value of list element.

python list example

That are given 4 different list. now our goal is add item to this existing list. Here given 4 different type of method to add value into existing list.

Using concatenate : that is simple and very useful method. + (plus operator) are used to combine two list and result as return a new list. first list are initial contain 3 element. after add more three element new list contain 6 element. see in this image.

python add list item

note that + operator are combine a two different lists that are depends upon the order of list. observed that in given statement (first=first + ['D','E','alphabet']) are perform two operation. first is combine and returning the result is assign to first list.

Using append() function: that is straightforward way to add single element at last of list. that are append a given element at last position.

python add second list item

so imagine that what does happen when provide a another list to append() function. That means given a separate list as parameter of this function. then this will create a another list and passable this reference to last index. see this example.

listItem=['A','to', 'z']
#add new item to listItem
listItem.append(['python','code'])

#Display values
print(listItem)
Output
['A', 'to', 'z', ['python', 'code']]

This example are very important. there are existing one list inside another list. so how to access inside list element.

python multi list

Note that multilist internally as separate list and its reference are used to another list. understand the sense of that second internal list are index also start with zero. and possible to access that list element by its index. see this example.

listItem=['A','to', 'z']
#add new item to listItem
listItem.append(['python','code'])

#Display zero index value of second inside list
print(listItem[3][0])
Output
python

similar way access another element. if you are learn about c and c++ array then it's similar to 2D.

Using of insert function : insert is very very special. that accepting two parameter value first is position to add new list element. and other is value of index.

third=["c","c++"]

print("Before Added List is")
print("third list :",third)

#Method 3 using insert function
third.insert(1,'Python')

print("After Added List is")
print("third list :",third)
Output
Before Added List is
('third list :', ['c', 'c++'])
After Added List is
('third list :', ['c', 'Python', 'c++'])
python insert list

When adding a new element in given location the list are modified its index value.

Using extend function : extend function are used to add list item in end position. for example

fourth=[1]

print("Before Added List is")
print("fourth list :",fourth)

#Method 4 using extend function
fourth.extend(['Ok',1])

print("After Added List is")
print("fourth list :",fourth)
Output
Before Added List is
('fourth list :', [1])
After Added List is
('fourth list :', [1, 'Ok', 1])

Operation of Python List

There are various type of operation can perform of list data. but here are given three main operations such as searching, deleting, and updating value of list items.

Searching

searching is technique to find particular element within the list. that is depends on compare the value and its index. that means if we know about value of list element so easily to get key value .if we know about key(index) of list element then can get its value.

python are providing few function to perform search operation on list.

index() function

index is accept one parameter. that is the value of list in this case. for example

#index     0     1     2         3       4    5     6  
codeList=['c','c++','python2','python3','c','java','c++']

#Display value index
print(codeList.index("python3"))
print(codeList.index("java"))
print(codeList.index("c++"))
print(codeList.index("c"))
Output
3
5
1
0

Index function are compare the value of given list if value is exist then returning its index key. if there are two or more than two value are same in a list then it will return first value index.

so what happening when passing undefined list item to this index() function. it will produce an error. for example.

#index     0     1     2         3       4    5     6  
codeList=['c','c++','python2','python3','c','java','c++']

print(codeList.index("Python3"))
Output
Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print(codeList.index("Python3"))
ValueError: 'Python3' is not in list

find out "python3" is exist in list but "Python3" are not. so what are work on a existing value.

cout() function

When counting similar items of list so we can use in count() function. normally this function are accept 3 parameters. but when working on list item only one parameter are used. syntax are given below.

 itemList.count("value")

In given syntax, itemList is an variable which are store the item of list after that using of dot operator are used in to count function and this function are accept string of list item. for example.

#index     0     1     2         3       4    5     6  
codeList=['c','c++','python2','python3','c','java','c++']

#count occurrence of list value item
print(codeList.count("c"))
print(codeList.count("c++"))
print(codeList.count("data"))
print(codeList.count("java"))
Output
2
2
0
1

Note that this function is returning an integer value that are resultant occurance of given string in list. if value are not exist then it will returning 0 value.

Note that when list is exist true and false boolean value and integer value (0,1) that it will assume that (True==1) and (False ==0) are similar. for example.

#List value
listItem=[0,1,2,True,False,7,1,True,False]

print(listItem.count(True)) # count 1,True,1,True =4
print(listItem.count(1)) # count 1,True,1,True =4
print(listItem.count(False)) # count 0,False,0 =3
print(listItem.count(0)) # count 0,False,0 =3
Output
4
4
3
3

Delete and Removing list item

There are several way to delete(remove) list items. here given three different ways.

using del statement

del are use to remove single and hole list. when removing of single element so need to provide specific index to remove list element. see its syntax

 del listName[index]

for example

#List value
listItem=[0,1,2,3,4,5]
print(" Before delete list ")
#display list item
print(listItem)

#del statement to remove index 3 element
del listItem[3]

print(" After delete list index 3")
print(listItem)
Output
 Before delete list 
[0, 1, 2, 3, 4, 5]
 After delete list index 3
[0, 1, 2, 4, 5]

Note that before list contain 6 item elements. and del statement are used to remove 3'rd index element. In given below image is showing a structure before delete list element.

Before delete list

After removing index 3 list is look like this.

After remove 3rd index list

Note that after the delete element list are contain gap between index-2 and index 4 that. but managing this gap and make a new list are do this task by del statement.

Using pop() function

This function are remove last element of list. for example.

#List value
listItem=[1,2,3,4,5]
print(" Before Pop List ")
#display list item
print(listItem)

#delete last list element
listItem.pop() 

print(" After pop list ")
print(listItem)
output
 Before Pop List 
[1, 2, 3, 4, 5]
 After pop list 
[1, 2, 3, 4]
Using remove() function

remove() function are used to delete specific index element of in list. this function are accept one parameter value. this value are indicate which element will is remove.

#List value
listItem=[0,1,2,3,4,5]
print(" Before remove List ")
#display list item
print(listItem)

#delete second index
listItem.remove(2) 

print(" After remove second index of list ")
print(listItem)
Output
 Before remove List 
[0, 1, 2, 3, 4, 5]
 After remove second index of list 
[0, 1, 3, 4, 5]

List Advance Operation

There are most of cases we can need to modified list to specified format and perform some special operation. here given few example.

Combine multilist to single list.

#list
[1, 2, [7, 8, 6], [11, 22, 33, [90, 100, ['A', 'B']]]]

#accepted Output
[1, 2, 7, 8, 6, 11, 22, 33, 90, 100, 'A', 'B']

Suppose given list is combination of multi-list. in this situation we are try to convert inner multi list using following approach.

#convert muli-list to single one

#given list
listData=[1,2,[7,8,6],[11,22,33,[90,100,['A','B']]]]
print(listData)
newList=[] #create empty list
def combine(listData):
  for data in listData:
    if (type(data)==list):
      #newList+=data #when data is not mutilist
      combine(data)
    else:
      newList.append(data)
      
combine(listData)
print(newList)
Output
[1, 2, [7, 8, 6], [11, 22, 33, [90, 100, ['A', 'B']]]]
[1, 2, 7, 8, 6, 11, 22, 33, 90, 100, 'A', 'B']

In this example using a new list that are store result and also using recursion. so time and space complexity of this program is O(n).

copy or clone of a list

#copy a list
import copy
list1=[1,2,3,4,5]
list2=list1[:] #first way
list3=list1.copy() #second way using copy
list4=list(list1) #third way
list5=copy.copy(list1) #fourth way
Example clone python list


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved