Python List

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

compare two lists

# initializing our lists list1 = [1, 2, 4, 3, 5] list2 = [1, 2, 4, 3, 6] # printing lists print ("The first list is : " + str(list1)) print ("The second list is : " + str(list2)) # using sum() + zip() + len() to check if # lists are equal if len(list1)== len(list2) and len(list1) == sum([1 for i, j in zip(list1, list2) if i == j]): print ("The lists are identical") else : print ("The lists are not identical")

slicing

>>> l=[1,2,3,4,5] >>> l[1:3] [2, 3] >>> l[1:-2] [2, 3] >>> l[-3:-1] # negative indexes in slicing [3, 4] >>> s="Hello World" >>> s[1:3] 'el' >>> s[:-5] 'Hello ' >>> s[-5:] 'World'

Shallow copying Modify the list with new list colours

Assgined new list colours1 = ["red", "green"] colours2 = colours1 colours2 = ["rouge" ,"vert"] print colours1 colours1 = ["red", "green"] colours2 = colours1 colours2[1] = "blue" print colours1

How to count the occurrences of a perticular element in the list?

Example # 1: weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon'] print(weekdays.count('mon')) Output: 3 Example # 2: weekdays = ['sun','mon','tue','wed','thu','fri','sun','mon','mon'] print([[x,weekdays.count(x)] for x in set(weekdays)])

What is the output, Suppose list1 is [1, 3, 2], What is list1 * 2 ?

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

all the elements of the list that are less than 5.

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] for num in a: if num <5: print num

remove the duplicate elements from the given list?

a = [1,2,2,3] list(set(a))

Swap the First and Last Value of a List?

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: 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]

Find the Second Largest Number in a List?

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: Enter number of elements:4 Enter element:23 Enter element:56 Enter element:39 Enter element:11 Second largest element is: 39

Shallow copying Replace old list with new list colours

colours1 = ["red", "green"] colours2 = colours1 colours2 = ["rouge" ,"vert"] print colours1

Duplicate List

def hasDuplicates(a): seen = set() for x in a : if x in seen: return True else: seen.add(x) return False print 'hasDuplicates([1,2,2,2,3])=' , hasDuplicates([1,2,2,2,3]) print 'hasDuplicates([1,3,3,3,8])=' , hasDuplicates([1,3,3,3,8])

Sore months ("Jan, Feb , Mar,April,May,June") in variable Months and iterate for loop over each value in Months. The current value of Months in stored in variable m

def main(): #use a for loop over a collection Months = ["Jan","Feb","Mar","April","May","June"] for m in Months: print(m) if __name__ == "__main__": main()

Function that will return new list with no duplicate elements a list

def removeDupl(inputList)" #we need an empty list before the loop secondList = [] for element in inputList: seondList.append(element) #so if there is no such element - add it to the list return secondList #lets check myList = ['hello', 'youtube', 'hello', 'youtube'] print myList myList = removeDupl(myList) print myList output: ['hello', 'youtube', 'hello', 'youtube'] output: ['hello', 'youtube']

calculate the sum of a list of numbers.

def sum(num): if len(num) == 1: return num[0] #with only one element in the list, sum result will be equal to the element. else: return num[0] + sum(num[1:]) print(sum([2, 4, 5, 6, 7])) output:24

write a function that sums all elements of a list and # returns them

def sum_list(my_list): count = 0 for number in my_list: count = count + number return count assert sum_list([1, 2, 3]) == 6 assert sum_list([1, 2, 3, 4]) == 10 print(sum_list([1, 2]))

remove the duplicate elements from the given list?

f = [1,2,3,3,3,,2,4,4] f =set(f) print(f) f = list(f)

Deep Copying update the list with new value in sublist using index slice function

from copy import deepcopy print "Deep Copy" list1=['a','b',['ab','ba']] list2=deepcopy(list1) list2[2][1] = "d" list2[0] = "c"; print list 2 print list 1

randomize the items of a list in place in Python?

from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x) The output of the following code is as below. ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag']

Print a new List by doing a left rotate on the given list

import collections a=[4,5,6,7] d = collections.deque(a) d.rotate(3) print d

Print All elements which are multiples of 4

l =[4,8,12,16,20,7,81,92,83,78] for i in l: if not (i%4): print(i)

Given two lists x, y , print two new lists as output Using the slice operator

l1=[1,2,3,4,5] l2=[6,7,8,9,10] print(l1[1:-1]) print(l2[1:-1])

Find the maximum number from the given list of number and replace that element with the maximum number in the list

l=[10,20,30,40,50] max=0 for i in l: if i>max: max=i i=0 index=0 for i in l: l[index]=max index+=1 print(l)

Find the maximum number from the given list of number

l=[10,20,30,40,50] max=0 for i in l: if i>max: max=i print(i)

Sort list by ascending order

li = [9,8,7,6,4,3,2] s_li = sorted(li) print(s_li)

sort a numerical list in Python.

list = ["2", "5", "7", "8", "1"] list = [int(i) for i in list] list.sort() print (list)

remove the last object from a list

list = ["2", "5", "7", "8", "1"] list.pop(obj=list[-1]):

Print True if First and Last elements are equal and odd numbers in the list

list = [3,2,3,3] if (list[0]==list[-1]) and (((list[-1])%2) and ((list[0]))%2): print("%d is a odd number" %(int(list[0])))

Print SUM of ALL Elements in the given list

list = [3,2,3,3] sum =0 for i in list: sum+=i print(sum)

Print True if FIRST ELEMENT OR LAST ELEMENT IS DIVISIBLE BY 4 IN THE LIST

list = [4,2,3,4] if not ((list[-1])%4) and not ((list[0])%4): print("Divisible by 4")

Shallow copying update the list with new value using index slice function

list1 = ['a','b','c','d'] list2=list1[:] print list2 list2[1] = 'x' print list2 print1

multiply every element of a list by three and assign it to new list

list1 = [3,4,5] multiplied = [item*3 for item in list1] print multiplied

Shallow copying update the list with new value in sublist using index slice function

list1=['a','b',['ab','ba']] list2=list1[:] list2 = 'c' list2[2][1] = 'd' print(list1)

Print True if the SUM of first and last elements are equal in the TWO LISTS

list1=[3,2,3,3] list2=[3,2,3,3] if (list1[-1]+list1[0]) == (list2[-1]+list2[0]): print("equal")

Print All Duplicate value in list

list_num = [1,2,3,1,2,4,5,6,7] hash = [] for i in range(10): hash.append(0) print(hash) for i in list_num: hash[i]+=1 print(hash) print(list_num) i=0 index=0 for i in hash: if i > 1: print(index) index+=1

Take first letter of each word and make a list out of it

listofwords = ["this", "is","a","list","of","words"] items=[word[0] for word in llistofwords] print items

Filters - Program to filter out only the even items from a list

my_list = [1,5,4,6,8,11,3,12] new_list = list(filter(lambda x:(x%2 ==0), my_list)) #output : [4,6,8,12] print(new_list)

How to convert a list into a set?

weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue'] listAsSet = set(weekdays) print(listAsSet) output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])

How to convert a list into a tuple?

weekdays = ['sun','mon','tue','wed','thu','fri','sat'] listAsTuple = tuple(weekdays) print(listAsTuple) output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')

How to convert a list into a string?

weekdays = ['sun','mon','tue','wed','thu','fri','sat'] listAsString = ' '.join(weekdays) print(listAsString)


Ensembles d'études connexes

Oregon 30-Hour Real Estate Finance Course Week 2

View Set

Chapter 48 Skin integrity and Wound Care

View Set

Sociology 3rd Test Sample Questions

View Set

The Recording Process - Lecture 2 (Chapter 2)

View Set

Chapter 40: Disorders of the Female Genitourinary System-Patho Level 3

View Set

English Short Story Test 2 Review

View Set

Chapter 25 Law- Agency Liability Concepts

View Set