Python. Lists

11.2.3.1 create a list;
11.2.3.2 organize the output of a string using the split() and join() methods;
11.2.2.1 perform access to the elements of strings, lists, tuples;
11.2.3.6 determine the difference between different data structures;

Python. Lists

What are Lists?

We have already examined collections such as sets and strings. Now we will get acquainted with another type of collection - the list (list). Lists are widely used in programs.

List is an ordered composite data type, a mutable collection of objects of arbitrary types.

Create Lists

There are two ways to create an empty list:

# the first way to create an empty list
lst = list()
print(lst) # will print an empty list []

# second way to create an empty list
lst = []
print(lst) # will print an empty list []

To create a non-empty list, you need to add elements in square brackets, separated by commas.

animals = ["tiger", "fox", "wolf", "rabbit"]
print(animals) # will print ['tiger', 'fox', 'wolf', 'rabbit']
numbers = [35, 23, 19, 30]
print(numbers) # will print [35, 23, 19, 30]

The main properties of the list in comparison with the collections that we already know:

  • A list stores multiple items under the same name (like many)
  • List items can be repeated (as opposed to a set)
  • List items are ordered and indexed, slice operation is available (as in string)
  • List items can be modified (as opposed to a string)
  • The elements of the list can be values ​​of any type: integers and real numbers, strings, and even other lists.

Generating lists

Remember what happens when a string is multiplied by a number.
s = "!" * 5
print(s) # will print: !!!!!

The operation of multiplying by a number is applicable to lists as well. For example, we need to create a list that initially contains ten zero elements. All items in the list will be the same, and unlike sets, each of them will be a separate item in the list.

lst = [0] * 5
print(lst) # will print: [0, 0, 0, 0, 0]
# another example
print(['x', 'y'] * 3) # will print: ['x', 'y', 'x', 'y', 'x', 'y']

Indexing lists

The elements of the list and the characters of the string have their indices; therefore, unlike the sets, the order of the elements in the list is important !!!

lst = ["tiger", "fox", "wolf", "rabbit"]
print(lst[2]) # will print: wolf
print(lst[0]) # will print: tiger
print(lst[7]) # will print an error message IndexError: list index out of range
numbers = [2, 5, 8, 13, 21]
print(numbers[1] + numbers[3]) # will print: 18

Adding items to the list

If the add method is used to add an element to a set, it means the item is added.

The append method is used to add elements to the end of lists since all the elements are indexed.

lst = ["tiger", "fox", "wolf", "rabbit"]
lst.append("lion") # item is added to the end of the list
print(lst) # will print: ['tiger', 'fox', 'wolf', 'rabbit', 'lion']

We can also extend the existing list with any iterable (enumerable) object using the extend method.

lst = [1, 2, 3]
another_lst = [4, 5, 6]
lst.extend(another_lst)
print(lst) # will print: [1, 2, 3, 4, 5, 6]

If we expand the list with a string, then each character of the string becomes a separate element of the list.

lst = []
another_lst = "world"
lst.extend(another_lst)
print(lst) # will print: ['w', 'o', 'r', 'l', 'd']

The list can be expanded with a set since a set is also iterable.

lst = [1, 2, 3]
another_set = {'w', 'o', 'r', 'l', 'd'}
lst.extend(another_set)
print(lst) # will print: [1, 2, 3, 'w', 'o', 'r', 'l', 'd']

Modifying a list item

Unlike strings, individual list items can be modified.

lst = [1, 2, 5]
lst[1] = 7
print(lst) # will print: [1, 7, 5]

However, many of the operations that you can perform on other collections can be performed on lists as well.

lst = [1, 2, 3]
print(len(lst)) # print the length of the list
lst += [4, 5] # Lists can be added like strings
print(lst) # will print: [1, 2, 3, 4, 5]
if 1 in lst: # you can check if the list contains an element    
    print('Is in the list')
else:
    print('Not in the list')

Displaying list items

Like strings, the elements of a list can also be iterated over in a for loop using indices and iterating over the elements.

lst = ["tiger", "fox", "wolf", "rabbit"]
for i in range(len(lst)):                 # use the indices of the list items
    print('List item', i + 1, '-', lst[i])# will be printed: all # list items in turn
for elem in lst:          # use the elements of the list
    print(elem)          # will be printed: all elements of the list in turn
-------------------------------------------------- ------
List item 1 - tiger
List item 2 - fox
List item 3 - wolf
List item 4 - rabbit
tiger
fox
wolf
rabbit

Populating list items with input

n = int(input())                  # input the number of items in the list
a = []                            # declaration of an empty list
print('Enter', n, 'values:')
for i in range(n):          # determining the number of iterations (repetitions)    
    a.append(input())       # add the input to the list
print('The result is a list of strings:', a) # output of the resulting list

Slices of lists

Since the list contains indexed items, you can apply slices to them as well as to strings.

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']
spring = months[2:5] # spring == ['March', 'April', 'May']
for month in spring:
    print(month)

Slices can also be used to assign new values ​​to list items. For example, if we decide to translate the names of the summer months into English, we can do this using a slice.

months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']
months[5:8] = ['JUNE', 'JULY', 'AUGUST']
print(months)
----------------------------------------
['January', 'February', 'March', 'April', 'May', 'JUNE', 'JULY', 'AUGUST', 'September', 'October', 'November', 'December']

Removing items

The del function can be used to remove items from a list.

a = [1, 2, 3, 4, 5, 6]
del a[2]                 # deleting element with index 2
print(a)                 # will print: [1, 2, 4, 5, 6]

The item at the specified index is removed, and the list is rebuilt.

The del function also works with slices: for example, you can delete all elements at even positions in the original list.

a = [1, 2, 3, 4, 5, 6]
del a[::2]
print(a) # will print: [2, 4, 6]

Lists vs. Arrays

Lists are sometimes called arrays, but this is wrong since arrays store data of only one type and are in memory in one sequence, and the elements of a list can contain values ​​of different types and can be scattered around memory randomly, so working with lists is slower than with arrays, but at the same time lists are more flexible in programming.

Questions:

Exercises:

 

Категория: Programming languages | Добавил: bzfar77 (22.11.2021)
Просмотров: 4399 | Рейтинг: 5.0/4
Всего комментариев: 0
avatar