2

I have following tuple:

vertices = ([0,0],[0,0],[0,0]);

And on each loop I want to append the following list:

[x, y]

How should I approach it?

2
  • 1
    FYI you don't need to end your lines with a semi-colon in python. Commented Feb 28, 2014 at 20:36
  • 1
    It's a bit unclear what you're asking, could you give an example of what you want? How do you want them appending? etc? Commented Feb 28, 2014 at 20:37

5 Answers 5

5

You can't append a list to a tuple because tuples are "immutable" (they can't be changed). It is however easy to append a tuple to a list:

vertices = [(0, 0), (0, 0), (0, 0)]
for x in range(10):
    vertices.append((x, y))

You can add tuples together to create a new, longer tuple, but that strongly goes against the purpose of tuples, and will slow down as the number of elements gets larger. Using a list in this case is preferred.

Sign up to request clarification or add additional context in comments.

Comments

1

You can't modify a tuple. You'll either need to replace the tuple with a new one containing the additional vertex, or change it to a list. A list is simply a modifiable tuple.

vertices = [[0,0],[0,0],[0,0]]

for ...:
    vertices.append([x, y])

Comments

1

You can concatenate two tuples:

>>> vertices = ([0,0],[0,0],[0,0])
>>> lst = [10, 20]
>>> vertices = vertices + tuple([lst])
>>> vertices
([0, 0], [0, 0], [0, 0], [10, 20])

Comments

1

You probably want a list, as mentioned above. But if you really need a tuple, you can create a new tuple by concatenating tuples:

vertices = ([0,0],[0,0],[0,0])
for x in (1, 2):
    for y in (3, 4):
        vertices += ([x,y],)

Alternatively, and for more efficiency, use a list while you're building the tuple and convert it at the end:

vertices = ([0,0],[0,0],[0,0])
#...
vlist = list(vertices)
for x in (1, 2):
    for y in (3, 4):
        vlist.append([x, y])
vertices = tuple(vlist)

At the end of either one, vertices is:

([0, 0], [0, 0], [0, 0], [1, 3], [1, 4], [2, 3], [2, 4])

Comments

0

Not sure I understand you, but if you want to append x,y to each vertex you can do something like :

vertices = ([0,0],[0,0],[0,0])

for v in vertices:
    v[0] += x
    v[1] += y

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.