Python Forum
Sub: Python-3: Better Avoid Naming A Variable As list ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sub: Python-3: Better Avoid Naming A Variable As list ?
#1
While examining various alternatives for extracting dictionary content into a list, it is seen that in some of the web sites, list itself gets used as the name of a variable. For example:

"""
Python Code-01-Start
"""
dict = { 'Geeks': 10, 'for': 12, 'Geek': 31 }  
list = [] 

for i in dict: 
   k = (i, dict[i]) 
   list.append(k) 
  
print(list) 
#Output: [('Geeks', 10), ('for', 12), ('Geek', 31)]

"""
Python Code-01-End
"""
On its own, this code snippet works fine & gives the desired result. However, any subsequent code snippet involving use of list() function, attracts error. Sample code:

"""
Python Code-02-Start
""" 
mdict = {"A":50,"B":60,"C":70}

keylist = list(mdict)
print(keylist)

"""
Python Code-02-End
"""
Error:
Error Message on IDLE Python Shell-3.7.4 Traceback (most recent call last): File "<<>>", line <<>>, in <module> keylist = list(mdict) TypeError: 'list' object is not callable
If in first code block we replace the variable name list by mlist, the problem disappears and we get the correct output for second code snippet too i.e.
Output:
#Output: ['A', 'B', 'C']
Conclusion: Even though list does not formally feature in Python-3 keywords, and there are some instances of its actually being used as variable name, it would seem prudent to avoid doing so.

Esteemed members might like to look into it & offer their views.

adt
A.D.Tejpal
Reply


Messages In This Thread
Sub: Python-3: Better Avoid Naming A Variable As list ? - by adt - Aug-28-2019, 05:03 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Split string using variable found in a list japo85 2 2,200 Jul-11-2022, 08:52 AM
Last Post: japo85
  naming entities(city abbreviations) tirumalaramakrishna 1 1,867 May-06-2022, 11:22 AM
Last Post: jefsummers
  Avoid third party functions to wrote my python code into system debug-log? mark 9 3,892 Apr-09-2022, 08:41 PM
Last Post: mark
  An IF statement with a List variable dedesssse 3 23,016 Jul-08-2021, 05:58 PM
Last Post: perfringo
  Python Style and Naming Variables rsherry8 3 3,155 Jun-07-2021, 09:30 PM
Last Post: deanhystad
  How to define a variable in Python that points to or is a reference to a list member JeffDelmas 4 3,722 Feb-28-2021, 10:38 PM
Last Post: JeffDelmas
  Create variable and list dynamically quest_ 12 6,621 Jan-26-2021, 07:14 PM
Last Post: quest_
  Naming the file as time and date. BettyTurnips 3 4,785 Jan-15-2021, 07:52 AM
Last Post: BettyTurnips
Question Matching variable to a list index Gilush 17 8,785 Nov-30-2020, 01:06 AM
Last Post: Larz60+
  Python linter Pylance: What does "(variable): List | Unbound" mean? Drone4four 1 8,000 Oct-23-2020, 08:31 PM
Last Post: bowlofred

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020