Untitled
unknown
plain_text
2 years ago
3.0 kB
7
Indexable
list.py # Creating and printing lists def my_list(): dog_breeds = ['corgi', 'labrador', 'poodle', 'jack russell'] print(dog_breeds) # ['corgi', 'labrador', 'poodle', 'jack russell'] list_out_of_string = list('danger!') print(list_out_of_string) # ['d', 'a', 'n', 'g', 'e', 'r', '!'] # list_out_of_integer = list(235) # TypeError: 'int' object is not iterable # a string is an example of an iterable object # an integer is an example of a non-iterable object # A list itself is also an iterable object. # Features of lists: # Lists can store duplicate values as many times as needed. # They can contain different types of elements def features_of_lists(): on_off_list = ['on', 'off', 'on', 'off', 'on'] print(on_off_list) # ['on', 'off', 'on', 'off', 'on'] different_objects = ['a', 1, 'b', 2, [1, 2, 3]] languages = ['Python', 'JAVA', 'C++', 'JavaScript'] # Append new language to the list languages.append('Ruby') print('List of programming languages: ' + ', '.join(languages)) # List of programming languages: Python, JAVA, C++, JavaScript, Ruby # Remove the first occurrence of a value on_off_list.remove('off') print(on_off_list) # ['on', 'on', 'off', 'on'] def length_of_list(): numbers = [1, 2, 3, 4, 5] print(len(numbers)) # 5 empty_list = list() empty_list = [] print(len(empty_list)) # 0 single_element_list = ['danger!'] print(len(single_element_list)) # 1 multi_elements_list = list('danger!') print(len(multi_elements_list)) # 7 def reading_input(): read = list(input()) # 1 2 3 string print(read) # ['1', ' ', '2', ' ', '3', ' ', 's', 't', 'r', 'i', 'n', 'g'] my_list() features_of_lists() reading_input() ######################################################### indexes.py # Positionally ordered collections of elements are usually called sequences, and both lists and strings belong to them # Indexes are used to access elements within a sequence def indexes_of_elements(): colors = ['red', 'green', 'blue'] first_elem = colors[0] # 'red' second_elem = colors[1] # 'green' third_elem = colors[2] # 'blue' pet = "cat" first_char = pet[0] # 'c' second_char = pet[1] # 'a' third_char = pet[2] # 't' def potential_pitfalls(): colors = ['red', 'green', 'blue'] pet = "cat" print(colors[3]) # IndexError: list index out of range print(pet[3]) # IndexError: string index out of range colors[1] = 'white' print(colors) # ['red', 'white', 'blue'] pet[0] = "b" # TypeError: 'str' object does not support item assignment def negative_indexes(): colors = ['red', 'green', 'blue'] last_elem = colors[-1] # 'blue' second_elem = colors[-2] # 'green' first_elem = colors[-3] # 'red' pet = "cat" last_char = pet[-1] # 't' second_char = pet[-2] # 'a' first_char = pet[-3] # 'c' # 0 1 ... len-2 len-1 # -len -len+1 ... -2 -1
Editor is loading...
Leave a Comment