python extend or append a list when appropriate

Is there a simple way to append a list if X is a string, but extend it if X is a list? I know I can simply test if an object is a string or list, but I was wondering if there is a quicker way than this?

Asked by: Aida268 | Posted: 30-11-2021

Answer 1

mylist.extend( [x] if type(x) == str else x )

or maybe the opposite would be safer if you want to catch things other than strings too:

mylist.extend( x if type(x) == list else [x] )

Answered by: Chloe777 | Posted: 01-01-2022

Answer 2

I do not think so. extend takes any iterable as input, and strings as well as lists are iterables in python.

Answered by: Maria902 | Posted: 01-01-2022

Answer 3

buffer = ["str", [1, 2, 3], 4]
myList = []

for x in buffer:
    if isinstance(x, str):
    elif isinstance(x, list):
        print("{} is neither string nor list".format(x))

A better way would be using try-except instead of isinstance()

Answered by: Elise592 | Posted: 01-01-2022

Similar questions

python - Celery appropriate for this task?

This query is related to my Google Summer of Code project. Basically, I have a master node which delegates build tasks to a number of specified image building nodes. Right now, I do it using a manual, 'scp', folllowed by remote execution using 'ssh' strategy. So, I do not have any scheduling or task distribution - automag...

The most appropriate way to use Neo4j from Python in 2015

I'm using latest community Neo4j (2.2.0-M03) for storing my graphs. I'm interested in accessing it from Python. According to the official Neo4j documentation, there are several alternatives. From what I have understood by checking the docs, playing around a bit, and checking

python - Render to Html with appropriate values in django

I having a dictionary a = {'name': u'45445454', 'tracks': [{'A_TITLE': u'abb', 'IS': u'144', 'PN': u'3', 'T_TITLE': u'123'}, {'A_TITLE': u'abb', 'IS': u'45454454', 'PN': u'3', 'T_TITLE': u'225'}, {'A_TITLE': u'ggg', 'IS': u'232', 'PN': u'000', 'T_TITLE': u'555'}]...

python - Is Django is an appropriate tool for what I'm trying to do?

I have experience using HTML/CSS/Javascript and Python separately, but I'm completely lost on how to use both together (if that's even a thing). I have a Python file that can take input, calculate a value and return it. I thought my final result would be a webpage coded using HTML/CSS, that took a user input, inserted it somehow into that Python file and displayed the output. When I began reading about using Pytho...

Wrong Python module should throw appropriate error

I am using the Python module psutil, where I am using the psutil dummy module in the code. For example, Python 2.7.3 (default, Oct 26 2016, 21:01:49) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import psutil >>> psutil.sensor() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' o...

Easy and appropriate setup of a python script

What's the appropriate way to setup a python environment automatically without using pip/setuptools? I'm required to do this for a project and I'm not allowed to 'install' anything on the server. I don't have permissions for that and it's a script that will be used by multiple users. I need to set up the PYTHONPATH so modules can be imported in the package as well as create symbolic links for my command lin...

In Python Flask: What are appropriate places to store data?

This question already has answers here:

python - How do I take appropriate action after i detect an object in my camera?

I want to run a normal software using object detection, i can detect an object or color with openCV but after that i can not take any action. like i want to push a button whenever camera detect any color or object. with this code i can detect any yellow color object but i can't take any action after that. import cv2 import numpy as np cap = cv2.VideoCapture(0) while True: _, frame =

python - Is it appropriate to train W2V model on entire corpus?

I have a corpus of free text medical narratives, for which I am going to use for a classification task, right now for about 4200 records. To begin, I wish to create word embeddings using w2v, but I have a question about a train-test split for this task. When I train the w2v model, is it appropriate to use all of the data for the model creation? Or should I only use the train data for creating the model?

Why would my code be an appropriate style for Java, but not for Python

Why would my code be an appropriate style for Java, but not for Python? dct=getDictionary() if dct.has_key(3): invokeTriples(dct[3]) postProcessForTriples() print("Done for triples") if dct.has_key(7): invokeSeptuples(dct[7]) postProcessForOthers() print("All done!") Personally, I don't see the problem. Can you explain what she meant by 'appropriate'? And maybe giv...

python - Which of these scripting languages is more appropriate for pen-testing?

Closed. This question is opinion-based. It is not c...

Help me find an appropriate ruby/python parser generator

The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the tracing capabilities ( activated by setting $RD_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules. The thing is, it has to be written in python or in ruby, and have a verbose mo...

Would python be an appropriate choice for a video library for home use software

I am thinking of creating a video library software which keep track of all my videos and keep track of videos that I already haven't watched and stats like this. The stats will be specific to each user using the software. My question is, is python appropriate to create this software or do I need something like c++.

Is Python appropriate for algorithms focused on scientific computing?

python - How do I determine the appropriate check interval?

I'm just starting to work on a tornado application that is having some CPU issues. The CPU time will monotonically grow as time goes by, maxing out the CPU at 100%. The system is currently designed to not block the main thread. If it needs to do something that blocks and asynchronous drivers aren't available, it will spawn another thread to do the blocking operation. Thus we have the main thread being almost tot...

arrays - Most appropriate data structure (Python)

I'm new to Python and have what is probably a very basic question about the 'best' way to store data in my code. Any advice much appreciated! I have a long .csv file in the following format: Scenario,Year,Month,Value 1,1961,1,0.5 1,1961,2,0.7 1,1961,3,0.2 etc. My scenario values run from 1 to 100, year goes from 1961 to 1990 and month goes from 1 to 12. My file therefore has 100*29...

python - Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?

What do numpy arrays provide when performing time based calculations where state matters. In other words, where what has occurred in earlier or later in a sequence is important. Consider the following time based vectors, TIME = np.array([0., 10., 20., 30., 40., 50., 60., 70., 80., 90.]) FLOW = np.array([100., 75., 60., 20.0, 60.0, 50.0, 20.0, 30.0, 20.0, 10.0]) TEMP = np.array([300., 310...

python - Finding appropriate cut-off values

I try to implement Hampel tanh estimators to normalize highly asymmetric data. In order to do this, I need to perform the following calculation: Given x - a sorted list of numbers and...

python - What is an appropriate way to datamine the total number of results of a keyword search?

newbie programmer and lurker here, hoping for some sensible advice. :) Using a combination of Python, BeautifulSoup, and the Bing API, I was able to find what I wanted with the following code: import urllib2 from BeautifulSoup import BeautifulStoneSoup Appid = #My Appid query = #My query soup = BeautifulStoneSoup(urllib2.urlopen("" + Appid + "&query=" ...

python - Defining appropriate number of processes

I have a python code treating a lot of apache logs (decompress, parse, crunching numbers, regexping etc). One parent process which takes a list of files (up to few millions), and sends a list of files to parse to workers, using multiprocess pool. I wonder, if there is any guidelines / benchmarks / advices which can help me to estimate ideal number of child process ? Ie. having one process per core...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python