Python - Lists
Challenge 9
Creating a list
>>> cars = []
>>> print(cars)
[]>>> cars = ['Ford', 'Vauxhall', 'BMW',]
>>> print(cars)
['Ford', 'Vauxhall', 'BMW']>>> squares = [1, 4, 9, 16,]
>>> print(squares)
[1, 4, 9, 16]Get item from a list
>>> print(cars[2])
'BMW'>>> print(cars[0])
'Ford'>>> print(cars[-1])
'BMW'>>> print(cars[0:2])
['Ford', 'Vauxhall']Add item to a list
>>> cars.append('Toyota')
>>> print(cars)
['Ford', 'Vauxhall', 'BMW', 'Toyota']Replace an item in a list
>>> print(cars)
['Ford', 'Vauxhall', 'BMW', 'Toyota']
>>> cars[2]('Nissan')
>>> print(cars)
['Ford', 'Vauxhall', 'Nissan', 'Toyota']Delete an item in a list
>>> print(cars)
['Ford', 'Vauxhall', 'Nissan', 'Toyota']
>>> cars.remove('Nissan')
>>> print(cars)
['Ford', 'Vauxhall', 'Toyota']Delete a list
>>> print(cars)
['Ford', 'Vauxhall', 'Nissan', 'Toyota']
>>> cars.clear()
>>> print(cars)
[]Various other methods
list.pop()
list.index(value)
list.count(value)
list.sort()
list.reverse()
list.copy()
Python Challenge 9
Write a program that will generate a random playing card when the return key is pressed.
Rather than generate a random number from 1 to 52. Create two random numbers – one for the suit and one for the card.
Python Challenge 9
Write a program that will generate a random playing card when the return key is pressed.
#imports
import random
#constants
suit = ["Spades", "Hearts", "Clubs", "Diamonds"]
number = ["Ace", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"]
print("Press 'q' to exit the program... ")
choice = ' '
choice = input('Press "Enter" to get a new random playing card...\n')
while choice != 'q' :
cardNumber = number[random.randint(0, 12)]
cardSuit = suit[random.randint(0, 3)]
print("The card drawn was the \"{} of {}\". " .format(cardNumber, cardSuit))
choice = input('Press "Enter" to get a new random playing card...\n').lower()Python Challenge 9
By David James
Python Challenge 9
Lists in Python 3
- 261