Lists

Lists:
Lists in Python are one of the most versatile collection object types available. The other two types are dictionaries and tuples, but they are really more like variations of lists.
Python lists do the work of most of the collection data structures found in other languages and since they are built-in, you don’t have to worry about manually creating them. Lists can be used for any type of object, from numbers and strings to more lists. They are accessed just like strings (e.g slicing and concatenation) so they are simple to use and they’re variable-length i.e they grow and shrink automatically as they’re used.

>>>list=[1,2,3,4,5]
>>>print list
OUTPUT:
[1,2,3,4,5]
>>>print list[0]   #print the list item at index 0
1
>>>list.pop()  #remove and print the last item
5

Here’s a list of common list operations:
⦁ L1=[] An empty list
⦁ L2=[0,1,2,3] Four item
⦁ L3=[‘abc’,[‘def’,’ghi’]] Nested sublists
⦁ L2[n],L3[n][j] L2[n:j],len(L2) Index,slice,length
⦁ L1+L2,L2*3 Concatenate,repeat
⦁ for x in L2,3 in L2 Iteration,membership
⦁ L2,append(4),L2.sort(),L2.index(1),L2.reverse() Methods:grow,sort,search,reverse,etc.
⦁ del L2[k],L2[n:j]=[] Shrinking
⦁ L2[n]=1,L2[n:j]=[4,5,6] Index assignment,slice assignment
⦁ range(4),xrange(0,4)Make lists\tuples of integers

1.Example for Iterating through a list

>>>mylist=["one","two","three"]
>>>for x in mylist:
print "number"+x

OUTPUT:
number one
number two
number three

Adding List Elements:
Adding new items to a list is extremely easy. you simply tell the list to add it.Same thing with sorting a list.

Example for Adding List Elements:

l =[]; 
n = int(input("Enter the number of elements in the list")); #Number of elements will be entered by the user 
for i in range(0,n): # for loop to take the input 
l.append(input("Enter the item?")); # The input is taken from the user and added to the list as the item 
print("printing the list items...."); 
for i in l: # traversal loop to print the list items 
print(i, end = " "); 
 
Output:
Enter the number of elements in the list 5
Enter the item?1
Enter the item?2
Enter the item?3
Enter the item?4
Enter the item?5
printing the list items....
1  2  3  4  5 
Translate »