1

I'm trying to take a list in python and append (in a tuple) a few variables and also in the tuple add every item from another list, so that each individual item in the list has it's own place in the tuple.

Basically adding more elements to a tuple, from another list.

I tried running a for loop inside the tuple but of course that didn't work. I've seen someone do something similar but not sure how it actually works.

items = []
listy = []
var1, var2, var3 = 0, 1, 2
items.append((var1, var2, var3, for l in listy))

I just get an invalid syntax error. Again, this is just a visualization of what I want to happen. Here is another example of how I see it looking:

list[var1, var2, var3, listy[0], listy[1], listy[n]]

Thanks for your input. Sorry if this is a stupid question, I haven't been using python too long but couldn't find anything specific online.

Isaak Johnson
  • 129
  • 3
  • 8

3 Answers3

2

In python 3 you can unpack listy into the tuple as:

items.append((var1, var2, var3, *listy))

In python 2 you'll need to do an explicit add:

items.append((var1, var2, var3) + tuple(listy))
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
1

A tuple in Python is an immutable data structure, so you cannot add to it.

What you can do is create a list, add to that and then turn it into a tuple. Or you can concatenate two tuples. Like this:

result = (var1, var2, var3) + tuple(listy)
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
1

I'm having difficulty understanding your question but I think that you're looking for the extend method for lists (tuples are immutable, you cannot append to them or extend them), maybe with usage of * to expand iterables inside of other iterables. Here are some examples:

items = []
var1, var2, var3 = 0, 1, 2
listy = [var1, var2, var3] 

items.extend((var1, var2, var3))  # Extend with a tuple
items.extend(listy)  # Extend with a list
items.extend((var1, var2, *(i*-1 for i in listy)))  # Usage of * to expand a tuple into a tuple

print(items)  # should print [0, 1, 2, 0, 1, 2, 0, 1, 0, -1, -2]
Michael
  • 2,344
  • 6
  • 12