Lists (Arrays)
Lists are used to hold a list of elements. They could be strings, numbers, etc. Normally, you would use an array type, but python does not support arrays.
list.py
# create a list of car names cars = ['Ford', 'Nissan', 'Toyota'] # access first car name car = cars[0] print(f'The first car is {car}') # how many cars are there print(f'There are {len(cars)} cars') # print all the cars print('Cars:') for car in cars: print(car) print('-----') # add a car to the list cars.append("Honda") print('Cars after append(Honda):') for car in cars: print(car) print('-----') print("Done.")
Output:
The first car is Ford There are 3 cars Cars: Ford Nissan Toyota ----- Cars after append(Honda): Ford Nissan Toyota Honda ----- Done.
Links
Exercises (5 mins)
-
Use a for loop to find a user number in a list.
find_a_number.py
numbers = [10, 15, 20, 25, 30, 35] # Enter a number # Convert the number to a int # Set a flag to false for number in numbers: if number == : found = True if found == True: print("Found the number in the list.") else: print("Sorry, did not find the number.") print('Done.')
Output:
Enter a number: 20 Found the number in the list. Enter a number: 22 Sorry, did not find the number.
-
Use a for loop to sum all the numbers in a a list.
sum_numbers.py
numbers = [10, 15, 20, 25, 30, 35] # intialize a sum to 0 for number in numbers: # add the numbers in the list # print the sum print('Done.')
Output:
The sum is 135
-
Find the smallest and largest number in a list.
sum_numbers.py
numbers = [0, 2, 5, 100, -1, 4, 8, -5 ] # intialize smallest to the first element of the list # initialize largest to the first element of the list for number in numbers: # find the smallest number # find the largest number # print the smallest number # print the largest number print('Done.')
Output:
The smallest number is -5 The largest number is 100