Python Lists

Lists are one of 4 built-in data types in Python used to store collections of data.Lists are used to sequentially store data of various types data . Every element in the list has an address given to it, which is known as the Index. The index value ranges from 0 to the last element, which is referred to as the positive index. Negative indexing, which begins at -1, allows you to access elements from last to first.

Example :

a = []
print(a)
b = [1,2,3,"hello",4.56]
print(b)
print(b[0],b[2],b[4])
print(b[5])
print(b[-1],b[-5])
print(b[-10])

Output :

[]
[1, 2, 3, "hello, 4.56]
1 3 4.56
Python IndexError: list index out of range
4.56 1
Python IndexError: list index out of range

Adding Element to List

For adding any type of data or element to the list we use .append() method and If we want to add element to a specific place we can use .index() method

a = [1,2]
print(a)
a.append(3)
a.append(4)
print(a)
a.index(3,10)
print(a)

Output:

[1, 2]
[1, 2, 3, 4]
[1, 2, 3, 10, 4]

Adding a List or multiple elements to List

for adding a list or multiple element to a list , we use .extend() method.

a = [1, 2, 3]
b = [4, 5]
print(a)
print(b)
a.extend(b)
print(a)
print(b)

Output :

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

Removing element from List

There are two ways to remove element from a list :-

  1. Remove by index : We can remove element(s) by list index by using .pop() method.
  2. Remove by element : We can remove element(s) by list element by using .remove() method
# Remove by Index using .pop() method
a = [1, 2, 3, 4]
print(a)
a.pop(2) # remove element from index 2
print(a)
# Remove element by data/element using .remove() method
a.remove(1)
print(a)

Output : –

[1, 2, 3, 4]
[1, 2, 4]
[2, 4]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s