Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

In [1]:

a = [1,2,3,4,5]

In [2]:

len(a)

Out[2]:

pop()

In [3]:

# Synatx : <listVariable>.pop(<index of element you want to remove>)

In [4]:

Out[4]:

[1, 2, 3, 4, 5]

In [5]:

a.pop(2)

Out[5]:

In [6]:

Out[6]:

[1, 2, 4, 5]

sort()

In [13]:

# Syntax : <listVariable>.sort()

# It simply sorts the elemets present in the list in ascending order.

# Must Have Condition : The elements present in the list should be homogenous.

In [14]:

x = [1,6,4,2,3,8,9,5]
In [15]:

x.sort()

In [16]:

Out[16]:

[1, 2, 3, 4, 5, 6, 8, 9]

In [25]:

z = ["Divyanshu","Divyanshu","Divya","Yash","Suhani","Aditi"]

In [26]:

z.sort()

In [27]:

Out[27]:

['Aditi', 'Divya', 'Divyanshu', 'Divyanshu', 'Suhani', 'Yash']

In [17]:

y = ["Divyanshu",1,2,2.5]

In [18]:

y.sort()

--------------------------------------------------------------------------
-
TypeError Traceback (most recent call las
t)
<ipython-input-18-a65c6cb3e953> in <module>
----> 1 y.sort()

TypeError: '<' not supported between instances of 'int' and 'str'

In [28]:

# To sort a list in descending order, we have to pass a parameter to the sort function:

# called "reverse".

# Syntax : <listVariable>.sort(reverse = True)

In [29]:

x = [1,6,4,2,3,8,9,5]
In [30]:

x.sort(reverse = True)

In [31]:

Out[31]:

[9, 8, 6, 5, 4, 3, 2, 1]

In [32]:

a = [1,2,6,5,3]

In [33]:

a.sort()

In [34]:

Out[34]:

[1, 2, 3, 5, 6]

In [35]:

b = [1,2,6,5,3]

In [36]:

b.sort(reverse = False)

In [37]:

Out[37]:

[1, 2, 3, 5, 6]

In [38]:

z = ["Divyanshu","Divya","Yash","Suhani","Aditi"]

In [39]:

z.sort(reverse = True)

In [40]:

Out[40]:

['Yash', 'Suhani', 'Divyanshu', 'Divya', 'Aditi']


reverse()

In [44]:

# If we want to reverse the order of elements in a list.

# We can use reverse() function.

# Syntax : <listVariable>.reverse()

In [45]:

z = ["Divyanshu","Divya","Yash","Suhani","Aditi"]

In [46]:

z.reverse()

In [47]:

Out[47]:

['Aditi', 'Suhani', 'Yash', 'Divya', 'Divyanshu']

Slice Operator

In [48]:

# Syntax : <listvariable>[start:end]

In [49]:

a = [1,2,3,4,5,6,7,8,9,10,11,12]

In [50]:

a[3:9]

Out[50]:

[4, 5, 6, 7, 8, 9]

In [51]:

a[1:10]

Out[51]:

[2, 3, 4, 5, 6, 7, 8, 9, 10]

In [52]:

# Syntax : <listvariable>[start:end:step]
In [53]:

a[1:10:2]

Out[53]:

[2, 4, 6, 8, 10]

In [54]:

a[1:10:1]

Out[54]:

[2, 3, 4, 5, 6, 7, 8, 9, 10]

In [55]:

# If I don't provide step value, the default value will be 1.

In [56]:

# If I don't provide any value for start, it will by default consider the first index o
f list.

# i.e. 0

In [57]:

a[:10]

Out[57]:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [60]:

# If I don't provide any value for end, it will by default consider the first index of
list.

In [62]:

a[5:]

Out[62]:

[6, 7, 8, 9, 10, 11, 12]

In [63]:

a[5::2]

Out[63]:

[6, 8, 10, 12]


In [64]:

a[:]

Out[64]:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

You might also like