Unable to create a tuple in a single statement by appending to list created by list comprehension

Viewed 45

Goal: Create a tuple consisting of the column headers of a pandas dataframe AND an additional column in a single, easy-to-understand statement.

For the example say:

df.columns = ['a', 'b', 'c']
fname = 'sample.txt'

I can create the tuple ('a', 'b', 'c', 'sample.txt') in three statements as follows:

y = [x for x in df.columns]
y.append(fname)
mytuple = tuple(y)

It's readable, but verbose. I can reduce this to two statements as:

y = [x for x in df.columns].append(fname)
mytuple = tuple(y)

This is not bad, but I still prefer to do it in one line. My thought A is a single line statement should work like this:

mytuple = tuple([x for x in df.columns].append(fname))

Alas, that yields the error:

TypeError: 'NoneType' object is not iterable

I also tried B (wild guess)

mytuple = tuple([[x for x in df.columns].append(fname)])

but that gives the wrong result

(None,)

I would like to know 3 things:

  1. Why does option A does not work as I think it should.
  2. Is there a way to do this (non-obtusely) in a single statement.
  3. If so, how is it done?
4 Answers

You don't need to create a list first; just use the argument unpacking operator:

mytuple = (*df.columns, fname)

list.append() mutates the list, but is returning None. This is the reason for your error. To write this in one line, use list concatenation instead of list.append():

mytuple = tuple([x for x in df.columns] + [fname])
mytuple = tuple(list(df.columns) + [fname])

Although, @kaya3 solution is probably the best one

Because .append() doesn't reutn anything (it returtns None).

This is how its done:

print(tuple([x for x in df.colums] + [fname]))

or if df.colums is a list already:

print(tuple(df.colums + [fname]))
Related