What is a List in Python? and some problems on lists.

 A Python list is a collection for items of all types. The List is Iterable and is a sequence as well.

For more on this topic please go to Iterables in Python. A list is mutable. Its contents can be changed.


How do you define a List?

  • l=[] creates an empty list
  • l=[1,2,3] creates a list of 3 elements.
  • l=list(<sequence>) where <sequence> would be any object that has the getitem() and len() methods.

Here are a few examples.
l=list()
print(l)
l=[1,2,3,5,4]
print(l)
l=list("Apple")
print(l)
l=[1,2,3,4]
l=list(l)
print(l)

Output


Varanasi Software Junction: Lists in Python



Adding elements to a list

The best way of elements to a list is by using the + operator.
Thus if we have a list l=[1,2,3]

Then we can add an element to the end by writing 
l=l+ [4]
Then l will become [1,2,3,4]
To add an element before you simply use 
l=[0] + l
l=[0,1,2,3,4] now

We can add more than one element as well
l=l +  [5,6,7]
l=[0,1,2,3,4,5,6,7] now.

append and  extend can be used for adding elements as well.
l=[1,2,3]
l.append(4)
l=[1,2,3,4]

l=[1,2,3,4]
print("Original List ",l)
l=l+ [5]
print("After right plus ",l)
l=[0] + l
print("After left plus ", l)
l.append(6)
print("After append " ,l)
l.extend([7,8,9])
print("After extend ",l)


Output

Varanasi Software Junction: Adding elements to a Python list



Removing elements from a list
Elements of a list can be removed by using the following functions.
1. pop() method removes the last element in a list. pop(1) will remove the element at position 1.
 l=[1,2,3,4]
print("original list",l)
l.pop()
print("Popped list ",l)
l.pop(1)
print("Popped list ",l)

Output

Varanasi Software Junction: Python List Pop

2. clear() nethod removes all elements from the list.
l=[1,2,3,4]
print("original list",l)
l.clear()
print("cleared list",l)

Output
Varanasi Software Junction: Python List Clear





End

Post a Comment

0 Comments

Me