How do I make two lists from one in Python 3?

Question:

There is a main_list containing the number of elements n, with 1 <= n <= 10 and two empty lists list1 and list2. Each element of the main_list contains two numbers a and b, one space apart, with 1 <= a <= 100 and 1 <= b <= 100. We need to extract the value a from each element of the main_list and add it to list1, and the value b to list2. Let's say

main_list==['3 5', '1 2', '1 7']

Need to get list1==[3,1,1] and list2==[5,2,7] I tried to do this:

#создаём список main_list
main_list=['3 5', '1 2', '1 7']
#создаём списки list1 и list2
list1=list2=[]
for i in range(0,len(main_list)):
    #добавляем новый элемент в list1
    list1.append('')
    #добавляем новый элемент в list2
    list2.append('')
    #из i-го элемента списка main_list создаём список
    modification_list=list(main_list[i])
    #создаём индекс-счётчик для этого списка
    a=0
    #читаем цифры до пробела и заносим их
    #в i-й элемент (он же недавно добавленный) списка list1
    while modification_list[a]!=' ':
        list1[i]=modification_list[a]
        a=a+1
    #перешагиваем через пробел
    a=a+1
    #читаем цифры от пробела до конца и заносим их
    #в i-й элемент (он же недавно добавленный) списка list2
    for b in range(a, len(modification_list)):
    list2[i]=modification_list[b]
#преобразуем полученные данные из строкового типа в целочисленный
list1[i]=int(list1[i])
list2[i]=int(list2[i])
#выводим значения на экран
print(list1)
print(list2)

But, after executing the program, I got this:

>>>
[5, 2, 7, '', '', '']
[5, 2, 7, '', '', '']

Help

Answer:

I haven’t read the code yet, but it’s immediately clear that if the conditions and the required result are specified in full, then it is very, very much too clever. Everything can be compressed into one or two lines:

args = ([int(y) for y in x.split()] for x in main_list)
list1, list2 = zip(*args)

The bottom line is this: the zip function merges in pairs the lists it takes as an argument, and we prepare these arguments using two generator expressions nested inside each other: the outer one main_list over the elements of main_list , the inner one parses the string into numbers.

(There are errors in the code that indicate a misunderstanding of the essence of python; I will write them down later (they were pointed out in the comment))


The essence of the error with list1=list2=[] is as follows. [] Is a list, a list is a mutable object. In this expression, it is created once and assigned to two variables list1 and list2. As a result, both variables point to the same list, and when append is called, respectively, the elements being added end up in the same list, regardless of whether list1 or list2:

>>> list1=list2=[]
>>> list1.append(4)
>>> list2
[4]
>>> list1 is list2
True

There is nothing like that for numbers, strings and other primitive types (as well as tuples, but not entirely): these are immutable types, objects of these types cannot be changed (you simply will not find such functions in Python), you can only write other objects into a variable. The above example can also be converted to create a new list in several ways, for example, like this:

>>> list1=list2=[]
>>> list1 = list1 + [4]  # сложение списков даёт новый независимый список
>>> list2
[]
>>> list1
[4]
>>> list1 is list2
False

But it's better to immediately create separate lists and not be smart:

>>> list1 = []; list2 = []
>>> list1 == list2
True
>>> list1 is list2
False
Scroll to Top