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

Rui*_*gyu 0 python list

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]])
Run Code Online (Sandbox Code Playgroud)

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")]

fre*_*ish 7

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

>>> x = 'test'
>>> [x]
['test']
>>> list(x)
['t', 'e', 's', 't']
Run Code Online (Sandbox Code Playgroud)

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

  • 因为[[x]`是一个包含*单个*项的列表,而`list(x)`创建一个由x的每个元素*每个*项组成的列表。比较“ [3]”和“ list(3)”(是的,一个起作用,另一个引发异常)。str很奇怪:您可以将字符串视为单个字符字符串的容器,因为Python没有专用的char类型。 (3认同)