Rui Tongyu
Rui Tongyu

Reputation: 89

Why do list() and [] combine strings differently?

This is the output of the code below

I was playing around with list() and [] to combine strings selected from the column names. Then I noticed some peculiar behaviors (shown below). Could someone please explain why Python interpret list() + [] OR [] + list() differently?

I tried to search what's the difference between list() and [], but none of the answers resolved my confusion.

# below is the output for census_df.columns
Index(['SUMLEV', 'REGION', 'DIVISION', 'STATE', 'COUNTY', 'STNAME', 'CTYNAME',
       'CENSUS2010POP', 'ESTIMATESBASE2010', 'POPESTIMATE2010',
       'POPESTIMATE2011', 'POPESTIMATE2012', 'POPESTIMATE2013',
       'POPESTIMATE2014', 'POPESTIMATE2015', 'NPOPCHG_2010', 'NPOPCHG_2011',
       'NPOPCHG_2012', 'NPOPCHG_2013', 'NPOPCHG_2014', 'NPOPCHG_2015',
       'BIRTHS2010', 'BIRTHS2011', 'BIRTHS2012', 'BIRTHS2013', 'BIRTHS2014',
       'BIRTHS2015', 'DEATHS2010', 'DEATHS2011', 'DEATHS2012', 'DEATHS2013',
       'DEATHS2014', 'DEATHS2015', 'NATURALINC2010', 'NATURALINC2011',
       'NATURALINC2012', 'NATURALINC2013', 'NATURALINC2014', 'NATURALINC2015'],
      dtype='object')



print(list(census_df.columns[9:15]) + [census_df.columns[6]])
print("\n")
print(list(census_df.columns[9:15]) + list(census_df.columns[6]))
print("\n")
print([census_df.columns[9:15]] + [census_df.columns[6]])
print("\n")
print([census_df.columns[6]] + list(census_df.columns[9:15]))
print("\n")
print(list(census_df.columns[6]) + list(census_df.columns[9:15]))
print("\n")
print(list(census_df.columns[6]) + [census_df.columns[9:15]])

I expected them to be ["col6", "col9"..."col14"]. Instead, sometimes it's:

["c", "o", "l", "6", "col9", "col10"..."col14"] OR ["c", "o", "l", "6", index(...dtype="object")]

Upvotes: 0

Views: 63

Answers (1)

freakish
freakish

Reputation: 56527

list() converts any iterable into a list. Strings are iterables:

>>> x = 'test'
>>> [x]
['test']
>>> list(x)
['t', 'e', 's', 't']

while [x] syntax creates a literal list with a single element x. These are not equivalent, not even close.

Upvotes: 7

Related Questions