7

I am trying to add a tuple of a (number, (tuple)), but it drops the outer tuple.

How do I change the code so that l1 comes out looking like L2? It appears to drop the outer tuple and convert it to list elements? How do I stop that? Better yet, why is it happening?

l1 = []
t1 = (1.0 , (2.0,3.0))
l1.extend((t1))
t2 = (4.0 , (5.0,6.0))
l1.extend(t2)
print(l1)

l2 = [(1.0, (2.0,3.0)),
      (4.0, (5.0,6.0))]
print(l2)

l1 comes out as [1.0, (2.0, 3.0), 4.0, (5.0, 6.0)]

l2 comes out as [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]

3 Answers3

3

Use append:

l1 = []
t1 = (1.0, (2.0, 3.0))
l1.append((t1))
t2 = (4.0, (5.0, 6.0))
l1.append(t2)
print(l1)

l2 = [(1.0, (2.0, 3.0)),
      (4.0, (5.0, 6.0))]
print(l2)
dmitryro
  • 3,463
  • 2
  • 20
  • 28
1

Changing it to append() does the trick.

l1 = []
t1 = (1.0 , (2.0,3.0))
l1.append((t1))
t2 = (4.0 , (5.0,6.0))
l1.append(t2)
print(l1)

l2 = [(1.0, (2.0,3.0)),
      (4.0, (5.0,6.0))]
print(l2)

l1 - [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]

l2 - [(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]

Append adds the data structure as is to the end of the list, extend extracts the iterables. To understand it better append vs. extend

Community
  • 1
  • 1
Abhirath Mahipal
  • 938
  • 1
  • 10
  • 21
0

You can do it using both extend() and append(). The problem with your code using extend() is that Python does not recognize () as a tuple, even if there is only one element in it. However, it does recognize (,) as an empty tuple:

l1 = []
t1 = (1.0 , (2.0,3.0))
# Note the extra comma
l1.extend((t1,))
t2 = (4.0 , (5.0,6.0))
# Note the extra enclosing parentheses and comma
l1.extend((t2,))
print(l1)

l2 = [(1.0, (2.0,3.0)),
      (4.0, (5.0,6.0))]
print(l2)

The other way, as Vedang Mehta has said, is to use append:

l1 = []
t1 = (1.0 , (2.0,3.0))
l1.append(t1)
t2 = (4.0 , (5.0,6.0))
l1.append(t2)
print(l1)

l2 = [(1.0, (2.0,3.0)),
      (4.0, (5.0,6.0))]
print(l2)

Both will give you the result of:

[(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
[(1.0, (2.0, 3.0)), (4.0, (5.0, 6.0))]
Moon Cheesez
  • 2,489
  • 3
  • 24
  • 38