List and Tuple

LIST

list=[1,2,"hello",4,5]

l[position_index]=something -- update value of element

slicing - also starts from 0

While performing slicing if we enter any out of bound values then it will not show an error. 

FUNCTIONS:

l.sort()= creates list in ascending order # eg. print(l.sort())

l.reverse()=reverse the order of elements in list

l.append(something)== add new items at end of list(individual item 1 or multiple)

l.insert(position_index,item to be added)== insert new item in between    [typeError if only 1 argument given] (if the positive index entered is bigger than list length then value gets added at last/end) 


l.pop(position_index)==remove item [if nothing specified then last item]   [can give index error]

pop function also returns the deleted element i.e. prints it in interactive mode(if used)

l.remove(element in list)== remove first occurrence item [value error if not in list][type error if not specified]

del l1[index/range]   [can give index error]

l.extend(list2)==add iterable as argument at the end (list, tuple, dictionaries, sets, strings)

l.reverse()==reverses the list

l.sort(reverse=True) [type error if all elements are not of same type]

l.index() [can give value error if element not found][first occurrence]    

l.clear()==deletes a complete list (parenthesis are supposed to be empty else type error)

l.count(element)==returns the no. of occurrence of an element.

max(l)

min(l)

sum(l) [the above 3 function can show type error if list is consisted of element of more than 1 data type]

lists are mutable:

****by aliasing both the lists gets stored in same memory location****

eg.

>>> l1=[1,2,3]

>>> l2=l1

>>> l2[0]="hello"

>>> l2

['hello', 2, 3]

>>> l1

['hello', 2, 3]

copying a list:

newlist=oldlist[:]

newlist=list(oldlist)

import copy

newlist=copy.copy(oldlist)


L1[-1:] =l2

Remove the last element of l1 and add all elements of l2 at end of l1

TUPLE(cannot update value)

t=(1,2,3,4)

Or even 

t=1,2,3,4 

**single item tuple t=(1,)

slicing - also starts from 0

TUPLE methods:

t.count(element, start, /end)==counts how many times element1 occur in tuple

t.index(element1)==gives the position_index of element1

len(t)

any(t)==true if not empty

min,max,sum

sorted(t) ==all elements get sorted and returns the result as a list[or list1=sorted(t) ]

so it doesn't make changes in original tuple

t1=t1+t2  


tuple use less memory as compared to a list

If a list is inside a tuple then value inside the list can be changed without an error 


y=[1]

x,=y   (tuple value swapping)

print(x)==1

print(type(x))==int


Comments

Popular posts from this blog

Dictionary and Sets in Python

Insertion Sort in python

Grid Printing Code for Python