Featured

    Featured Posts

List In Python Part-1

Python List Tutorial

There are a number of collection types in Python. While types such as int and str hold a single value, collection types hold multiple values

list data type:

§  If we want to represent a group of values as a single entity where insertion order required to preserve and duplicates are allowed then we should go for list data type.

1.     insertion order is preserved 
2.     heterogeneous objects are allowed 
3.     duplicates are allowed 
4.     Growable in nature 
5.     values should be enclosed within square brackets.


§  A list can be created by enclosing values, separated by commas, in square brackets.

 int_list = [1, 2, 3


string_list = ['abc', 'defghi']

§  A list can be empty:
empty_list = []

§  The elements of a list are not restricted to a single data type, which makes sense given that Python is a dynamic language.

mixed_list = [1, 'abc', True, 2.34, None]


§  A list can contain another list as its element:
nested_list = [['a', 'b', 'c'], [1, 2, 3]]


§  Lists are mutable, so you can change the values in a list.

names = ['Allen', 'Scott', 'James', 'Mack', 'Eric'
print(names)# the output will be ['Allen', 'Scott', 'James', 'Mack', 'Eric']
names[0]='Adam'
print(names) # the output will be ['Adam', 'Scott', 'James', 'Mack', 'Eric']

§  list is growable in nature. i.e. based on our requirement we can increase or decrease the size.

players=['Virat','Rohit','Sachin']
print(players) # the output will be ['Virat', 'Rohit', 'Sachin']
players.append('Shikhar')
print(players) # the output will be ['Virat', 'Rohit', 'Sachin', 'Shikhar']
players.remove('Virat')
print(players) # the output will be [ 'Rohit', 'Sachin', 'Shikhar']


Different Ways to Creating a list in Python


§  We can create empty list object as follows.
list=[]   
print(list)   
print(type(list))   
# The Output Will be
[]
<class 'list'>

list=[10,20,30,40,50]   
print(list)   
print(type(list))  

# The Output Will be
[10, 20, 30, 40, 50]
<class 'list'>

§  We can create list object with dynamic some element as follows.

                list=eval(input("Enter List:"))   
print(list)  
print(type(list))  

# The Output Will be
                Enter List:[10,20,30,40,50]
[10, 20, 30, 40, 50]
<class 'list'>


The list() function creates a list from an iterable object. 
An iterable may be either a sequence, a container that supports iteration.


l=list()
           print(l)
#Create an list by passing string as a sequence
l=list('hello')
print(l)

          Output:
['h', 'e', 'l', 'l', 'o']


§  Initializing a List to a Fixed Number of Elements

my_list1 = [None] * 5
my_list2 = ['test'] * 5
my_list3=[0]*5
print('my_list1=',my_list1)
print('my_list2=',my_list2)
print('my_list3=',my_list3)

Output:

my_list1= [None, None, None, None, None]
my_list2= ['test', 'test', 'test', 'test', 'test']
my_list3= [0, 0, 0, 0, 0]




§  The elements of a list can be accessed via an index, or numeric representation of their position. Lists in Python are zero-indexed meaning that the first element in the list is at index 0, the second element is at index 1 and so on:
names = ['Alice', 'Bob', 'Craig', 'Diana', 'Eric'
print(names[0]) # Alice 
print(names[2]) # Craig

§  Indices can also be negative which means counting from the end of the list (-1 being the index of the last element).

names = ['Allen', 'Scott', 'James', 'Mack', 'Eric'
print(names[-1]) # Eric 
          print(names[-4]) # Bob

Iterating over a list

§  You can iterate over the list elements using for loop like below:
for element in list:

       do operation

my_list=[1,2,3,4,5,6]
for element in my_list:    
    print (element)

§  You can also get the position of each item at the same time Using enumerate function:

my_list=[1,2,3,4,5,6]
for (index, item) in enumerate(my_list):
    print('The item in position {} is: {}'.format(index, item))

Output:

The item in position 0 is: 1
The item in position 1 is: 2
The item in position 2 is: 3
The item in position 3 is: 4
The item in position 4 is: 5
The item in position 5 is: 6



my_list=[1,2,3,4,5,6]
for i in range(0,len(my_list)):
 print(i,'->',my_list[i])

 Output:  

0 -> 1
1 -> 2
2 -> 3
3 -> 4
4 -> 5
5 -> 6



The + Operator

§  The + operator is Used to concatenating to List.

§  The simplest way to concatenate list1 and list2

merged = list1 + list2

list1=[1,2,3]
list2=[4,5,6]
merge_list=list1+list2
print('List1:- ',list1)
print('List2:- ',list2)
print('MergeList:- ',merge_list)

Output:

List1:-  [1, 2, 3]
List2:-  [4, 5, 6]
MergeList:-  [1, 2, 3, 4, 5, 6]



v If We want to merge List in such way as given below.


zip returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument2. sequences or iterables:

list1 = ['a1', 'a2', 'a3']
list2 = ['b1', 'b2', 'b3']
for a, b in zip(list1, list2):
    print(a, b)


§  If the lists have different lengths then the result will include only as many elements as the shortest one.

list1 = ['a1', 'a2', 'a3']
list2 = ['b1', 'b2', 'b3','b4']
for a, b in zip(list1, list2):
    print(a, b)


§  The * operator creates multiple copies of a string.

§  Replication – multiplying an existing list by an integer will produce a larger list consisting of that many copies11. of the original.


my_list1 = [1,2,3] * 3
my_list2 = ['a','b','c'] * 3
print('my_list1=',my_list1)
print('my_list2=',my_list2)

Output:

my_list1= [1, 2, 3, 1, 2, 3, 1, 2, 3]
my_list2= ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']



The in Operator

Checking Membership(List Contains):
§  By using in operator, we can check whether an item is in a list or not.

cities=['agra','delhi','jaipur','kanpur','lucknow']

print('agra' in cities)#The Output will be True

print('london' in cities)#The Output will be False

Slicing of a List (selecting parts of lists)

§  Slicing of a List means selecting a part of a list.

s[beginindex:endindex:step]

§  from begin index to end-1 index and every time update by step
§  default value for begin index is zero.
§  default value for end index is length of string.

s[begin:end:step]

§  step value can be either +ve or -ve.
§  if +ve then it should be forward direction (Left to Right).
§  If -ve then it should be backward direction (Right to Left).
§  If +ve forward direction from begin to end-1.
§  if -ve backward direction from begin to end+1.

Selecting a sublist from a list.
list1=[10,20,30,40,50,60,70]
print(list1[1:4])#The OutPut [20, 30, 40]
print(list1[3:7]);#The OutPut [40, 50, 60, 70]

v If you omit the first index, the slice starts at the beginning of the list. Thus, s[:m] and s[0:m] are equivalent:

s[:endindex]

list1=[10,20,30,40,50,60,70]
print(list1[:2])#The OutPut [10, 20]
print(list1[:3]);#The OutPut [10, 20, 30]

v if you omit the second index as in s[n:], the slice extends from the first index through the end of the list. This is a nice, concise alternative to the more cumbersome s[n:len(s)]:

s[beginindex:]

list1=[10,20,30,40,50,60,70]
print(list1[5:])#The OutPut [60, 70]
print(list1[6:]);#The OutPut [70]

v If you Omitting both indices return the original list.

list1[:]

list1=[10,20,30,40,50,60,70]
print(list1[:])#The OutPut[10, 20, 30, 40, 50, 60, 70]

v If the first index in a slice is greater than or equal to the second index, Python returns an empty list.

list1=[10,20,30,40,50,60,70]
print(list1[2:2])#The OutPut []
print(list1[4:2]);#The OutPut []

v Reversing a list with slicing
a = [10, 20, 30, 40, 50]
# steps through the list backwards (step=-1) 
b = a[::-1]
print('Original List=',a)
print('Reverse List= ',b)

Python List Tutorial








author

Author Name

Author Description!

Get Free Email Updates to your Inbox!

Post a Comment

www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews