Python: How to add single quotes to a long list - python

I want to know the quickest way to add single quotes to each element in a Python list created by hand.
When generating a list by hand, I generally start by creating a variable (e.g. my_list), assigning it to list brackets, and then populating the list with elements, surrounded by single quotes:
my_list = []
my_list = [ '1','baz','ctrl','4' ]
I want to know if there is a quicker way to make a list, however. The issue is, I usually finish writing my list, and then go in and add single quotes to every element in the list. That involves too many keystrokes, I think.
A quick but not effective solution on Jupyter NB's is, highlighting your list elements and pressing the single quote on your keyboard. This does not work if you have a list of words that you want to turn to strings, however; Python thinks you are calling variables (e.g. my_list = [1, baz, ctrl, 4 ]) and throws a NameError message. In this example, the list element baz would throw:
NameError: name 'baz' is not defined
I tried this question on SO, but it only works if your list already contains strings: Join a list of strings in python and wrap each string in quotation marks. This question also assumes you are only working with numbers: How to convert list into string with quotes in python.
I am not working on a particular project at the moment. This question is just for educational purposes. Thank you all for your input/shortcuts.

Yeah but then why not:
>>> s = 'a,b,cd,efg'
>>> s.split(',')
['a', 'b', 'cd', 'efg']
>>>
Then just copy it then paste it in
Or idea from #vash_the_stampede:
>>> s = 'a b cd efg'
>>> s.split()
['a', 'b', 'cd', 'efg']
>>>

The best way I found was:
>>> f = [10, 20, 30]
>>> new_f = [f'{str(i)}' for i in x]
>>> print(new_f)
['10', '20', '30']

You can take input as string and split it to list
For eg.
eg="This is python program"
print(eg)
eg=eg.split()
print(eg)
This will give output
This is python program
['This', 'is', 'python', 'program']
Hope this helps

It's been a while, but I think I've found a quick way following #U10-Forward's idea:
>>> list = ('A B C D E F G Hola Hello').split()
>>> print(list)
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'Hola', 'Hello']

Related

How to create whitespace between certain list elements?

I found a post asking about how to create whitespace in all list elements (Adding spaces to items in list (Python)), but I haven't found any posts asking about how to create whitespace in only specific elements of a list.
I'm wondering how to create a space between certain element characters in a list.
If I have a list like this:
lst = ['a', 'bb', 'c', 'bb']
How can I make a new list with a space between all 'bb' occurrences in a list to look like this?:
lst_new = ['a', 'b b', 'c', 'b b']
I've tried using .replace('bb', 'b" "b'), but I get 'b' and 'b' as separate list elements. Is there a specific notation for "whitespace" in Python? Or is there another way to approach this?
lst = ['a', 'bb', 'c', 'dd']
lst_new = []
for elem in lst:
if len(elem) > 1:
lst_new.append(' '.join(list(elem)))
else:
lst_new.append(elem)
print(lst_new)
Here's a very simple and easy to understand way to do it. The main idea is to check if the length of the elem is greater than 1, then use list to "split" the string. You can then join the string with a whitespace by using join.

Understanding the syntax of list comprehensions

I don't understand the syntax for list comprehension:
newList = [expression(element) for element in oldList if condition]
The bit I don't understand is (element). Let's say you had a following code:
List = [character for character in 'Hello world!']
print(list)
And then you will get:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Since the first character isn't quite an expression, what is it doing? Does it just mean that each item in the string is getting stored in a new list?
Python list comprehensions are for loops executed in a list to generate a new list.The reason python list comprehensions are evaluated backward from or right to left is because usually anything inside a bracket( [], {}, () ) in python is executed from right to left with just a few exeptions .Another thing to note is that a string is an iterable (lists,tuples, sets, dictionaries, numpy arrays) concatenating characters so it can be iterated over like a list.
List Comprhension form:
new_list = [item for item in my_list]
This will have the same effect:
for item in my_list:
my_list.append(item)
Since a strings is an iterable of characters you can do this:
my_list = [character for character in 'Hello world!']
print(list)
Output:
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Your list comprehension can also be written as:
my_list = []
for character in 'Hello world':
my_list.append(character)
print(my_list)
I am also pointing out that you shouldn't use built in methods(such as List) as variable names because when you do you overide them which will bar you from using that method in the future.
Here is a complete list of all builins as of python 3.9.6:
Let's understand the syntax for Python List Comprehensions using a few examples. Reference to complete documentation.
Basic usage: [<expression> for <item> in <iterable>]. In python, any object that implements the __next__() method is an iterable.
For example, List objects are iterables. Consider the following code:
list_a = [1, 2, 3]
list_b = [item for item in list_a] # [1, 2, 3]
list_c = [item + 1 for item in list_a] # [2, 3, 4]
list_d = [None for item in list_a] # [None, None, None]
Interestingly, a String object is also iterable. So when you iterate over a string, each item will be a character. This was the case in your example.
Now, coming to expressions. In python, any value (integer, float, char, etc) or any object is an expression. Just to clarify, the expression does not contain an equals symbol. This is an excellent answer to the question, "What is an expression in Python?".
I noticed that you had used (also pointed out in comments), list as the name of a variable. There are some keywords and names you should not use as variable names in Python. You can find the list of all such builtin names by: (refer this post for more details)
import builtins
dir(builtins)

How to remove apostrophes from a list in python?

I need to remove apostrophes -> ' <- from a list, within python, without using any add-ons, so only built in functions.
E.g. I need a list like:
lista = ['a', 'b', 'c', 'd']
into
lista = [ a, b, c, d]
I've tried using for with .replace or making the list into a string then replacing, but I haven't had anything work yet.
Any chance you could help?
You can use str.join() to concatenate strings with a specified separator.
For example:
>>> strings = ['A', 'B', 'C']
>>> print(', '.join(strings))
A, B, C
Furthermore, in your case, str.format() may also help:
>>> strings = ['A', 'B', 'C']
>>> print('strings = [{}]'.format(', '.join(strings)))
strings = [A, B, C]
You cannot remove apostrophes from a list because that's pretty much how you identify what a list is. However the apostrophes will not interfere with anything you do with the list. The apostrophes show that the elements are strings.

How to insert quotes in list to separate items?

NEW QUESTION:
So I have the list a:
a = ["abcd"]
but I want it to be:
a = ["a","b","c","d"]
The list I'm working with is very long (200 terms long; not 4)
So how do I make Python put a quote (") after each letter so they're individual terms? Because I don't want to manually do this for all my lists.
In [4]: a = ["abcd"]
In [5]: list(a[0])
Out[5]: ['a', 'b', 'c', 'd']
For previous version:
In [3]: a = ["a,b,c,d"]
In [4]: a[0].split(",")
Out[4]: ['a', 'b', 'c', 'd']
#Akavall's answer is very good, but in case you are dealing with a list with possible whitespace around the commas like this:
my_list = ["a, b, c, d"]
You'll want to strip the resulting items like so:
new_list = [x.strip() for x in my_list.split(',')]
For a list like this:
my_list = ["abcd"]
you'll need a different approach. Just do:
new_list = list(a[0])

Removing all elements containing (",") from a list

muutujad = list(input("Muutujad (sisesta formaadis A,B,C,...): "))
while "," in muutujad == True:
muutujad.remove(",")
print (muutujad)
My brain says that this code should remove all the commas from the list and in the end
the list should contain only ["A","B","C" ....] but it still contains all the elements. When i tried to visualize the code online, it said like [ "," in muutujad ] is always False but when i check the same command from the console it says it is True. I know it is a simple question but i would like to understand the basics.
You can use a list comprehension instead of a while loop:
muutujad = [elem for elem in muutujad if elem != ',']
Your if test itself is also wrong. You never need to test for == True for if in any case, that's what if does. But in your case you test the following:
("," in muutujad) and (muutujad == True)
which is always going to be False. In python, comparison operators like in and == are chained. Leaving off the == True would make your while loop work much better.
I'm not sure you understand what happens when you call list() on a string though; it'll split it into individual characters:
>>> list('Some,string')
['S', 'o', 'm', 'e', ',', 's', 't', 'r', 'i', 'n', 'g']
If you wanted to split the input into elements separated by a comma, use the .split() method instead, and you won't have to remove the commas at all:
>>> 'Some,string'.split(',')
['Some', 'string']
The best option here is to simply parse the string in a better way:
>>> muutujad = input("Muutujad (sisesta formaadis A,B,C,...): ").split(",")
Muutujad (sisesta formaadis A,B,C,...): A, B, C
>>> muutujad
['A', ' B', ' C']
str.split() is a much better option for what you are trying to do here.
What about list("Muutujad (sisesta formaadis A,B,C,...): ".replace(' ', ''))
Downvoter: I meant: this is how you do remove commas from string.
You do not convert your input from string to list and then remove your commas from the list, it's absurd.
you do: list(input('...').replace(' ', ''))
or you use split, as pointed out above.

Categories