arphsd
arphsd

Reputation: 31

Python - cloning a list

I want to make clones of every tuple in list1, so that the list in the tuple [1, 0, 1] is cloned with exactly one number differing from the original tuple, such that it adds to the newlist to make it:

[([0, 0, 1], 'a'), ([0, 1, 1], 'a'), ([1, 0, 0], 'a')]

However, what it is returning me is

[[[0, 1, 0], 'a'], [[0, 1, 0], 'a'], [[0, 1, 0], 'a']]. 
list1 = [([1, 0, 1], 'a')]
list2 = list1.copy()
newlist = []
for x in list2:
    for i in range(len(x[0])):
        new_x = list(x).copy()
        if x[0][i] == 1:
            new_x[0][i] -= 1
            newlist.append(new_x)
        elif x[0][i] == 0:
            new_x[0][i] += 1
            newlist.append(new_x)
print(newlist)

Upvotes: 2

Views: 88

Answers (3)

Boseong Choi
Boseong Choi

Reputation: 2596

You should shallow-copy x[0]. If not, the all inner-lists are same list, so they will share their elements.

I refactored two points:

  • use tuple unpacking in for-loop. for bits, character in ...
  • use bit inversion with boolean operator. int(not new_bits[i]) <- I assumed that the inner-lists only include 0 or 1.
original_list = [([1, 0, 1], 'a')]
new_list = []
for bits, character in original_list:
    for i in range(len(bits)):
        new_bits = bits.copy()
        new_bits[i] = int(not new_bits[i])
        new_list.append((new_bits, character))
print(new_list)

output:

[([0, 0, 1], 'a'), ([1, 1, 1], 'a'), ([1, 0, 0], 'a')]

Upvotes: 1

Nikolay Zakirov
Nikolay Zakirov

Reputation: 1584

list1 = [([1, 0, 1], 'a')]

newlist = []
for sublist in list1:
    for i in range(len(sublist[0])):
        new_item = sublist[0].copy()
        new_item[i] += 1
        new_item[i] %= 2
        newlist.append((new_item, sublist[1]))
print(newlist)

returns

[([0, 0, 1], 'a'), ([1, 1, 1], 'a'), ([1, 0, 0], 'a')]

Upvotes: 2

svfat
svfat

Reputation: 3373

You need to convert them back to the tuples

list1 = [([1, 0, 1], 'a')]
list2 = list1.copy()
newlist = []
for x in list2:
    for i in range(len(x[0])):
        new_x = list(x).copy() # <- converting to the list
        if x[0][i] == 1:
            new_x[0][i] -= 1
            newlist.append(tuple(new_x)) # <- converting to the tuple
        elif x[0][i] == 0:
            new_x[0][i] += 1
            newlist.append(tuple(new_x)) # <- converting to the tuple
print(newlist)

Upvotes: 2

Related Questions