Download as xlsx, pdf, or txt
Download as xlsx, pdf, or txt
You are on page 1of 10

Creating list:

1 Empty list: []
2 With Elements: [2] OR [2,1,5,3]
3 List comprehension: It is way to create another list from original list based on conditions.
Syntax: new_list=[expression for item in iterable condition_of_true]

1 new_lst=[x for x in lst] creates new list similar to old list


2 new_lst=[x for x in lst if "a" in x] creates new list from lst list containing elements w
3 new_lst=["Fruits" for x in lst] creates new list from lst list having same number o
4 new_lst=[x if x!="Banana" else "Orange" for x in lst] Here, outcome value is handled. If outc
new_lst=[x.upper() for x in lst] It creaes new list from lst list with same number of
4 List constructor: List() or List(iterable) iterable may be either a sequence, a co
List("abc") returns ['a','b','c'] List created from String object
List((1,2,3)) returns [1,2,3] List created from tuple

if lst=[1,5,2,7]
I. Mutable: (Changes elements of original list)
1 append: (Appends value at end of list)
lst.append(10)
2 Extend: (To append list at end of other list)
lst.extend([2,4,1])
3 insert: (inserts an element at an index location passed)
lst.insert(10,'val')
4 del: (deletes value(s) from string by passing index/deletes list and freeup memory)
del x deletes x list from memory
del x[1] deletes 2nd element from list -> [5,2,7]
del x[:1] deletes 1st element from list -> [5,2,7]
del x[2:] deletes elements from 2nd index till last index
del x[] invalid. Put index values when dealing with [ & ]
del x[:] It is same as empty list i.e. []. Deletes all elements of list starting from 1s
5 remove: (removes 1st match from list) (remove element by value)
lst.remove(5) this will return [1,2,7]
6 reverse: (reverses whole list)
lst.reverse() returns [7,2,5,1]
7 sort: (sorts elements in ascending order by default. Use 'revers' option to reverse in descending ord
lst.sort() returns [1,2,5,7]
lst.sort(reverse=True) returns [7,5,2,1]. Reverse sorting.
lst.sort(reverse=False) this is similar to lst.sort(). Ascending order.
Custom sorting:(sort based on length of strings)
def srt(str):
return len(str)

a=['dsd','ewwewe','a']
a.sort(key=srt)
print(a)
Output: ['a', 'dsd', 'ewwewe']
II. Immutable: (Does not change element of original list)
1 sorted: (similar to sort(), but does not change original list.) (all options of sort() can be applied to so
sorted(lst) sorts list in ascending order
sorted(lst,reverse=True) sorts list in descending order
Custom sort:
def srt_str(val):
return len(val)

x=['sssd','qe','sdsdsdss']
print(sorted(x,key=srt_str))
This will sort list based on logic written in function
2 +: (to concatenate/join 2 lists) (to concatenate lists of same data type)
x=[1,2,3]
b=[3,2,1]
print(a+b) it returns [1,2,3,3,2,1]
3 *: (replicates list number of times)
print(lst*2) this prints lst list 2 times i.e. [1,5,2,7,1,5,2,7]
4 min: (retruns value from list having minimum value)
print(min(lst)) prints -> 1
5 max: (returns max value from list)
print(max(lst)) prints->7
6 index: (returns position of 1st occurrence of an element from list)
print(lst.index(5)) prints index value-> 1
7 count: (returns number of time a value present in list)
print(x.count(5)) prints -> 1
8 sum: (returns sum of values from list)
print(sum(lst)) prints 15
9 in: (finds if an element is present in list) (Returns only boolean value)
print(10 in lst) prints False. Because 10 is not in list lst.
Observations on list:

1 Printing elements of list: Syntax: lst[index_w_r_t_0, index_w_R_t_1] or

print(lst[0]) 1
print(lst[0:0]) Empty list []
print(lst[0:1]) 1
print(lst[:1]) 1
print(lst[:]) All elements [1,5,2,7]
print(lst[:6]) Note that there are only 4 elements in list. But this is not error. Valid. But still it prin

Note: for lst list length is 4. So while slicing if indexes are too -ve or too +ve then there is no error.
e.g.
print(lst[-5:]) valid and prints all elements
print(lst[0:-10]) valid and prints all elements

2 Iterating over list:


for val in [1,2,3,4,5]:
print('Values are:{}'.format(val))
expression:Outcome/final_value which can be manipulated by functions; iterable:it can be list, tuple, set etc.; condition_of_tr

m lst list containing elements which have 'a' in it


m lst list having same number of elements but sets all element values to be 'Fruits'
come value is handled. If outcome is not banana then consider current value of x else sets outcome value to be Orange instead of Banana
m lst list with same number of elements but sets elements in Upper case.
may be either a sequence, a container that supports iteration, or an iterator object
ed from String object
ed from tuple

eeup memory) (first index is w.r.t. 0 & 2nd index passed is w.r.t.1) (remove element by index)

ements of list starting from 1st index till last index.

n to reverse in descending order, use 'key' to sort based on custom logic)

nding order.
ns of sort() can be applied to sorted())

ed on logic written in function to calculate length. This will sort list based on length of elements in ascending order.
lst[index_1,index_2] (index_1 should always be less than index_2)

not error. Valid. But still it prints all elements of list.

e then there is no error.


uple, set etc.; condition_of_true:conditions which filters items

be Orange instead of Banana


e.g. tpl=(3,70,10,4)
-They are ordered sequences of items like lists but They are immutable unlike lists.
-They can have items/elements of different type in the same tuple like list.

Empty tuple: var=() or var=tuple() use tuple function

Initialising tuple: a=(1,2,3,4,5) or a=1,2,3,4,5 or a,b,c=(10,20,30)

IMP: Tuple with single value:


a=(1,) or a=1, --valid
a=(1) or a=1 --Not a tuple

Accessing values from tuple:


Positive index: 0,1,2,3,..
Negative index: …,-4,-3,-2,-1

print(tpl[0]) first element


print(tpl[-1]) last element

Slicing tuple: Slicing tuple returns a new tuple with subset of original tuple.

print(tpl[0]) 1
print(tpl[0:0]) Empty tuple ()
print(tpl[0:1]) 1
print(tpl[:1]) 1
print(tpl[:]) All elements (1,5,2,7)
print(tpl[:6]) Note that there are only 4 elements in list. But this is not error. Valid. But

Note: for tpl tuple length is 4. So while slicing if indexes are too -ve or too +ve then there is no e
e.g.
print(tpl[-5:]) valid and prints all elements
print(tpl[0:-10]) valid and prints all elements

We cannot change values of existing tuple. Because they are immutable. Assigning new value to existing tuple value results in
However, we can only create new tuples per our requirement.

- Below statement will assign 10 to a, 20 to b & 30 to c.


a,b,c=10,20,30 or a,b,c=(10,20,30)

Iterating over Tuple:


for val in (1,2,3,4,5):
print('Values are:{}'.format(val)) prints:1,2,3,4,5

for index_val, actual_val in enumerate((1,2,3,4,5)):


print('Value at {} is {}'.format(index_val,actual_val))

Advantages of tuples over lists:


1 Tuples are faster than lists,
2 Tuples can be used as keys in Dictionaris but lists cannot be used,
3 Tuples can be used as values in sets but cannot use lists in it.
a,b,c=(10,20,30) or a,b,c=10,20,30

--Not a tuple

But this is not error. Valid. But still it prints all elements of list.

-ve or too +ve then there is no error.

o existing tuple value results in error.

Here, enumerate() function returns a tuples having index & actual value in it.

You might also like