Tuesday 17 October 2017

Python Lists & Lists Programs


Python lists
List is a sequence and a basic data structure.  A list may contain strings (text) and numbers.  A list is similar to an array in other programming languages, but has additional functionality.

·      Python lists are the data structure that is capable of holding different type of data.
·      Python lists are mutable i.e., Python will not create a new list if we modify an element in the list.
·      It is a container that holds other objects in a given order. Different operation like insertion and deletion can be performed on lists.
·      A list can be composed by storing a sequence of different type of values separated by commas.
·      A python list is enclosed between square([]) brackets.
·      The elements are stored in the index basis with starting index as 0.


We define lists with brackets []. To access the data, these same brackets are used.

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

# list with mixed datatypes
my_list = [1, "Hello", 3.4]

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

 List usage example:

#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
print(l[0])  # print first element
print(l[1])  # prints second element

Add/remove:
We can use the functions append() and remove() to manipulate the list.


#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)                        # prints all elements
l.append("Victoria")   # add element.
print(l)                        # print all elements
l.remove("Derp")       # remove element.
l.remove("Drake")     # remove element.
print(l)                       # print all elements.

Sort list:
We can sort the list using the sort() function.
#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
l.sort()     # sorts the list in alphabetical order
print(l)     # prints all elements

List in descending order, simply use the reverse() function.
#!/usr/bin/python
l = [ "Drake", "Derp", "Derek", "Dominique" ]
print(l)     # prints all elements
l.sort()    # sorts the list in alphabetical order
l.reverse() # reverse order.
print(l)     # prints all elements


List Comprehension: Elegant way to create new List:
·      List comprehension is an elegant and concise way to create new list from an existing list in Python.
·      List comprehension consists of an expression followed by for statement inside square brackets.
·      Here is an example to make a list with each item being increasing power of 2.

pow2 = [2 ** x for x in range(10)]

# Output: [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
print(pow2)

This code is equivalent to:
pow2 = []
for x in range(10):
   pow2.append(2 ** x)

A list comprehension can optionally contain more for or if statements. An optional if statement can filter out items for the new list. Here are some examples.

>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

List Index:
Example:

my_list = ['p','r','o','b','e']
print(my_list[0])
# Output: p

print(my_list[2])
# Output: o

print(my_list[4])
# Output: e

# Error! Only integer can be used for indexing
# my_list[4.0]

# Nested List
n_list = ["Happy", [2,0,1,5]]

# Nested indexing
print(n_list[0][1])  
# Output: a
 print(n_list[1][3])
# Output: 5


Negative indexing:
my_list = ['p','r','o','b','e']
print(my_list[-1])
# Output: e

print(my_list[-5])
# Output: p


How to slice lists in Python?

We can access a range of items in a list by using the slicing operator (colon).

my_list = ['p','r','o','g','r','a','m','i','z']
print(my_list[2:5])
# elements 3rd to 5th

print(my_list[:-5])
# elements beginning to 4th

print(my_list[5:])
# elements 6th to end

print(my_list[:])

# elements beginning to end


Python Built-in List Methods
append()   - Add an element to the end of the list
extend()    - Add all elements of a list to the another list
insert()      - Insert an item at the defined index
remove()   - Removes an item from the list
pop()         - Removes and returns an element at the given index
clear()        - Removes all items from the list
index()       - Returns the index of the first matched item
count()       - Returns the count of number of items passed as an argument
sort()          - Sort items in a list in ascending order
reverse()    - Reverse the order of items in the list
copy()        - Returns a shallow copy of the list



Some examples of Python list methods:

my_list = [3, 8, 1, 6, 0, 8, 4]
print(my_list.index(8))
# Output: 1
print(my_list.count(8))
# Output: 2
my_list.sort()
print(my_list)
# Output: [0, 1, 3, 4, 6, 8, 8]
my_list.reverse()
print(my_list)
# Output: [8, 8, 6, 4, 3, 1, 0]

Built-in List Functions
1
cmp(list1, list2)

Compares elements of both lists.
2
len(list)

Gives the total length of the list.
3
max(list)

Returns item from the list with max value.
4
min(list)

Returns item from the list with min value.
5
list(seq)

Converts a tuple into list.




List Related Programs:
===================
1. Program to Find Even elements in a List:
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evenlst = []
for num in a:
    if num % 2 == 0:
        evenlst.append(num)

print("the new even list is", evenlst)

ALITER:
evenlst = [number for number in a if number % 2 == 0]
print("the new even list is", evenlst)

2. Program to Print list having numbers less than 10
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numlst = []
for num in a:
    if num < 10:
        numlst.append(num)

print(numlst)

3. Program to find common elements between two lists
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# First convert the list to set
a = set([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
print(type(a))
b = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
print(type(b))
res = a.intersection(b)
print("common elements: ", res)


4. Program to find a new list having 1st and last element.
newlst = []
def test(lst):
    newlst.append(lst[0])
    newlst.append(lst[-1])
    print(newlst)
lst = [1,2,3,4,5,6,7]
test(lst)


5. Program to find if element is present in given list or not.
def find(ordered_list, element_to_find):
    for element in ordered_list:
        if element == element_to_find:
            return True
    return False

l = [1,2,3,4,5]
print(find(l,10))

6. Program to remove duplicate values from a list
lst = [1,1,2,3,4,5,4,2,10,15,5,6]
newlst = set(lst)
print(newlst)


7. Write a Python function to sum all the numbers in a list
def sum(lst):
    res = 0
    for i in lst:
        res += i
    return res
    
lst = [1,2,3,4,5,-1]
print(sum(lst))


8. Write a Python function that takes a list and returns a new list with unique elements of the first list
def unique_list(lst):
    x = []
    for a in lst:
        if a not in x:
            x.append(a)
    return x
   
lst = [1,2,3,3,4,4,5]
print(unique_list(lst))

9. Write a Python Program to Find the Largest Number in a List.

1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.

Code:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
a.sort()
print("Largest element is:",a[n-1])




Output:
1:
Enter number of elements:3
Enter element:23
Enter element:567
Enter element:3
Largest element is: 567

2:
Enter number of elements:4
Enter element:34
Enter element:56
Enter element:24
Enter element:54
Largest element is: 56


10. Write a Python Program to Find the Second Largest Number in a List

1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the second last element of the list.
5. Exit.

Code:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
a.sort()
print("Second largest element is:",a[n-2])




Output:
1:
Enter number of elements:4
Enter element:23
Enter element:56
Enter element:39
Enter element:11
Second largest element is: 39

2:
Enter number of elements:3
Enter element:23
Enter element:4
Enter element:67
Second largest element is: 23


11. Write a Python Program to Put Even and Odd elements in a List into Two Different Lists.

1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a different one.
5. Display the elements in both the lists.
6. Exit.


Code:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
even=[]
odd=[]
for j in a:
    if(j%2==0):
        even.append(j)
    else:
        odd.append(j)
print("The even list",even)
print("The odd list",odd)


Output:
1:
Enter number of elements:5
Enter element:67
Enter element:43
Enter element:44
Enter element:22
Enter element:455
The even list [44, 22]
The odd list [67, 43, 455]

2:
Enter number of elements:3
Enter element:23
Enter element:44
Enter element:99
The even list [44]
The odd list [23, 99]

12. Write a Python Program to Merge Two Lists and Sort it.

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Similarly, take in the elements for the second list also.
4. Merge both the lists using the ‘+’ operator and then sort the list.
5. Display the elements in the sorted list.
6. Exit.

Code:
a=[]
c=[]
n1=int(input("Enter number of elements:"))
for i in range(1,n1+1):
    b=int(input("Enter element:"))
    a.append(b)
n2=int(input("Enter number of elements:"))
for i in range(1,n2+1):
    d=int(input("Enter element:"))
    c.append(d)
new=a+c
new.sort()
print("Sorted list is:",new)

Output:
1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)

2:
Enter the number of elements in list 1 : 0
Enter the number of elements in list 2 : 3
Enter element 1 : 12
Enter element 2 : 12
Enter element 3 : 12
The union is :
[12]

13. Write a Python Program to Sort the List According to the Second Element in Sublist:

1. Take in a list containing sublists.
2. Using two for loops, use bubble sort to sort the sublists based on the second value of the sublist.
3. If the second element of the first sublist is greater than the second element of the second sublist, exchange the entire sublist.
4. Print the sorted list.
5. Exit.

Code:
a=[['A',34],['B',21],['C',26]]
for i in range(0,len(a)):
    for j in range(0,len(a)-i-1):
        if(a[j][1]>a[j+1][1]):
            temp=a[j]
            a[j]=a[j+1]
            a[j+1]=temp

print(a)

Output:
1:
[['B', 21], ['C', 26], ['A', 34]]

14. Write a Python Program to Find the Second Largest Number in a List Using Bubble Sort.

1. Take in the number of elements for the list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list using bubble sort.
4. Print the second last element of the sorted list which is the second largest number.
5. Exit.

Code:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=int(input("Enter element:"))
    a.append(b)
for i in range(0,len(a)):
    for j in range(0,len(a)-i-1):
        if(a[j]>a[j+1]):
            temp=a[j]
            a[j]=a[j+1]
            a[j+1]=temp
print('Second largest number is:',a[n-2])

Output:
1:
Enter number of elements:4
Enter element:56
Enter element:43
Enter element:78
Enter element:12
('Second largest number is:', 56)

2:
Enter number of elements:6
Enter element:23
Enter element:45
Enter element:94
Enter element:10
Enter element:34
Enter element:95
('Second largest number is:', 94)

14. Write a Python Program to Sort a List According to the Length of the Elements

1. Take in the number of elements for the first list and store it in a variable.
2. Take in the elements of the list one by one.
3. Then sort the list giving the length of the elements as the key.
4. Display the sorted list.
5. Exit.

Code:
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
    b=input("Enter element:")
    a.append(b)
a.sort(key=len)
print(a)

Output:
1:
Enter number of elements:4
Enter element:"Apple"
Enter element:"Ball"
Enter element:"Cat"
Enter element:"Dog"
['Cat', 'Dog', 'Ball', 'Apple']

2:
Enter number of elements:4
Enter element:"White"
Enter element:"Red"
Enter element:"Purple"
Enter element:"Orange"
['Red', 'White', 'Purple', 'Orange']

15. Write a Python Program to find Intersection of Two Lists.

1. Define a function which accepts two lists and returns the intersection of them.
2. Declare two empty lists and initialize them to an empty list.
3. Consider a for loop to accept values for the two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the second list also.
7. Find the intersection of the two lists.
8. Print the intersection.
9. Exit.

Code:
def intersection(a, b):
    return list(set(a) & set(b))

def main():
    alist=[]
    blist=[]
    n1=int(input("Enter number of elements for list1:"))
    n2=int(input("Enter number of elements for list2:"))
    print("For list1:")
    for x in range(0,n1):
        element=int(input("Enter element" + str(x+1) + ":"))
        alist.append(element)
    print("For list2:")
    for x in range(0,n2):
        element=int(input("Enter element" + str(x+1) + ":"))
        blist.append(element)
    print("The intersection is :")
    print(intersection(alist, blist))
main()

Output:
1:
Enter number of elements for list1:3
Enter number of elements for list2:4
For list1:
Enter element1:34
Enter element2:23
Enter element3:65
For list2:
Enter element1:33
Enter element2:65
Enter element3:23
Enter element4:86
The intersection is :
[65, 23]

2:
Enter number of elements for list1:2
Enter number of elements for list2:4
For list1:
Enter element1:3
Enter element2:4
For list2:
Enter element1:12
Enter element2:34
Enter element3:4
Enter element4:6
The intersection is :
[4]

16. Write a Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number.

1. Take the upper and lower range for the numbers from the user.
2. A list of tuples must be created using list comprehension where the first element is the number within the range and the second element is the square of the number.
3. This list of tuples is then printed.
4. Exit.

Code:
l_range=int(input("Enter the lower range:"))
u_range=int(input("Enter the upper range:"))
a=[(x,x**2) for x in range(l_range,u_range+1)]
print(a)

Output:
1:
Enter the lower range:1
Enter the upper range:4
[(1, 1), (2, 4), (3, 9), (4, 16)]

2:
Enter the lower range:45
Enter the upper range:49
[(45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401)]

17. Write a Python Program to Generate Random Numbers from 1 to 20 and Append Them to the List

1. Import the random module into the program.
2. Take the number of elements from the user.
3. Use a for loop, random.randint() is used to generate random numbers which are them appending to a list.
4. Then print the randomised list.
4. Exit.

Code:
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
    a.append(random.randint(1,20))
print('Randomised list is: ',a)

Output:
1:
Enter number of elements:3
('Randomised list is: ', [17, 4, 9])

2:
Enter number of elements:7
('Randomised list is: ', [16, 5, 18, 19, 6, 7, 20])

18. Write a Python Program to ort a List of Tuples in Increasing Order by the Last Element in Each Tuple

1. Take a list of tuples from the user.
2. Define a function which returns the last element of each tuple in the list of tuples.
3. Define another function with the previous function as the key and sort the list.
4. Print the sorted list.
5. Exit.

Code:
def last(n):
    return n[-1] 

def sort(tuples):
    return sorted(tuples, key=last)

a=input("Enter a list of tuples:")
print("Sorted:")
print(sort(a))

Output:
1:
Enter a list of tuples:[(2,5),(1,2),(4,4),(2,3)]
Sorted:
[(1, 2), (2, 3), (4, 4), (2, 5)]

2:
Enter a list of tuples:[(23,45),(25,44),(89,40)]
Sorted:
[(89, 40), (25, 44), (23, 45)]




19. Write a Python Program to Swap the First and Last Value of a List

1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Using a temporary variable, switch the first and last element in the list.
4. Print the newly formed list.
5. Exit.

Code:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
temp=a[0]
a[0]=a[n-1]
a[n-1]=temp
print("New list is:")
print(a)

Output:
1:
Enter the number of elements in list:4
Enter element1:23
Enter element2:45
Enter element3:67
Enter element4:89
New list is:
[89, 45, 67, 23]

2:
Enter the number of elements in list:3
Enter element1:56
Enter element2:34
Enter element3:78
New list is:
[78, 34, 56]

20. Write a Python Program to Remove the Duplicate Items from a List

1. Take the number of elements in the list and store it in a variable.
2. Accept the values into the list using a for loop and insert them into the list.
3. Use a for loop to traverse through the elements of the list.
4. Use an if statement to check if the element is already there in the list and if it is not there, append it to another list.
5. Print the non-duplicate items of the list.
6. Exit.

Code:
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=int(input("Enter element" + str(x+1) + ":"))
    a.append(element)
b = set()
unique = []
for x in a:
    if x not in b:
        unique.append(x)
        b.add(x)
print("Non-duplicate items:")
print(unique)

Output:
1:
Enter the number of elements in list:5
Enter element1:10
Enter element2:10
Enter element3:20
Enter element4:20
Enter element5:20
Non-duplicate items:
[10, 20]

2:
Enter the number of elements in list:7
Enter element1:10
Enter element2:20
Enter element3:20
Enter element4:30
Enter element5:40
Enter element6:40
Enter element7:50
Non-duplicate items:
[10, 20, 30, 40, 50]




For a Quick understanding of list basics and list comprehension watch the below videos.



4 comments:

  1. This article is a great article that I have seen in my python programming career so far, Its helps me a lot in performing function, and will continue to do so in the future.

    hire python developers in US

    ReplyDelete
  2. Thanks for sharing this informative article in detail on Python web development with suitable examples and screenshot. If you have any requirement to Hire Python Developers for your project on remote. Please visit us.

    ReplyDelete

Note: only a member of this blog may post a comment.