50 likes | 148 Views
Concatenate(join together) lists. list1 = ["gold", "gems ", "diamonds "] list2 = [“rubies", “emeralds ", “opals"] list3 = list1 + list2 print(list3) list1 +=list2 print(list1). Lists (Stuff we can do to lists). listofstuff = [“ant", “bear", “cat", “ dog“,”elephant ”] # assign by index
E N D
Concatenate(join together) lists list1 = ["gold", "gems ", "diamonds "] list2 = [“rubies", “emeralds ", “opals"] list3 = list1 + list2 print(list3) list1 +=list2 print(list1)
Lists (Stuff we can do to lists) listofstuff = [“ant", “bear", “cat", “dog“,”elephant”] # assign by index listofstuff[0] = “aardvark" print(listofstuff) # assign by slice listofstuff[3:5] = [“dolphin"] print(listofstuff) # delete an element del listofstuff[2] print(listofstuff) # delete a slice del listofstuff[:2] print(listofstuff)
#remove a score • score = 8 • if score in scores: • scores.remove(score) • print (scores) • scores.reverse() • print(scores) • # sort scores • scores.sort() • print(scores) • scores.sort(reverse = True) • print(scores) scores = [] #add a score newscore = 3 #append - adds to list scores.append(newscore) newscore = 8 scores.append(newscore) newscore = 4 scores.append(newscore) newscore = 2 scores.append(newscore) newscore = 5 scores.append(newscore) newscore = 8 scores.append(newscore) print(scores)
Other methods available for lists • scores.append(3) • scores.append(8) • scores.append(3) • print(scores) • print(scores.count(3)) • print(scores.index(3)) • scores.insert(7, 4) • print(scores) • scores.pop() • print(scores) • scores.remove(5) • print (scores) count(value) – counts the number of times value occurs in list index(value) – returns index of first occurrence of value insert(f,value)- inserts value at position f pop([f]) – returns value at position f and removes value from list. Without f, it pops the last element off the list remove(value) – removes first occurrence of value from the list
Generating Random Numbers import random def sl(list,new): if len(list) == 1: new.append(list.pop( )) return(new) else: x = random.randrange(0,len(list)) new.append(list.pop(x)) return(sl(list,new)) list = ["m","o","t","h","e","r"] new = [] print(sl(list,new))