0

I want to add a tuple in a list of tuples:

list1 = [('a', 'b'), ('c', 'd')]
tuple1 = ('e', 'f') # this is the tuple I want to add to the list above (list1).

list2 = list1.append(tuple1)

print(list2)

The result should be:

[('a', 'b'), ('c', 'd'), ('e', 'f')]

But instead, I'm finding:

None

  • `list.append` is an _inplace_ method for lists. It returns nothing and changes the list you call it on (here, list1). If you do `list2 = list1.append(tup1)`, then list2 will be None. Instead, print `list1`. And if you really don't want to do that operation _inplace_, you can do `list2 = list1 + [tuple1]` – Mateo Vial May 23 '22 at 22:30
  • The way I solved this. Was by adding the list 1 to a new list that contains de tuple1. Finally, I changed the order. ``` list1 = [('a', 'b'), ('c', 'd')] tuple1 = ('e', 'f') list2 = [tuple1] for i in list1: list2.append(i) list2.sort(key=tuple1.__eq__) print(list2) ``` Anyone has a better and more "pythonic" solution? – André Cerutti Franciscatto May 23 '22 at 22:50
  • 1
    Thank you, Mateo Vial. I really appreciate your comment. – André Cerutti Franciscatto May 23 '22 at 22:58

1 Answers1

0

You just did! Check out your list1

list1=[('a','b'),('c','d')]
list2 = list1.copy()
list2.append('e','f')
print(list2)

Explanation

  • list.append() method just returns None
Daniel Exxxe
  • 59
  • 1
  • 7