Why doesn't this join() work? [duplicate] - python

This question already has an answer here:
Why is the join built-in having no influence on my code?
(1 answer)
Closed 6 years ago.
I am not sure why this join() performed on a list doesn't work.
Here is my code:
list_1 = ['a', 'b', 'c']
print (list_1)
' '.join(list_1)
print (list_1)
And this is what is returned when I run it:
['a', 'b', 'c']
['a', 'b', 'c']

join() doesn't modify or reassign the list in place, instead it returns the string that it creates:
list_1 = ['a', 'b', 'c']
print (list_1)
list_1_string = ' '.join(list_1)
print (list_1_string)
From the str.join(iterable) docs:
Return a string which is the concatenation of the strings in the iterable iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

You are not storing the result of join...
list_1 = ' '.join(list_1)

str.join(<iterable>) returns a str. It doen't mutate the list to a str(!). Do the following,
s = " ".join(list_1)
print(s)

Related

List Compression prints [none, none, none] [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 1 year ago.
I have a question about list compressions within Python.
I am learning through Udacity and uploading my answers/code to an IDE (I could be wrong about it being an IDE) they have through my browser.
Before uploading I like to test my code to see if it actually works...as of now I am using Windows Powershell. So the code below is run on Powershell. But my question is...why when I run my code does it print [None, None, None, None] but when I print(new_list) I get ['a','b','c','d']
letters = ['A', 'B', 'C', 'D']
[new_list.append(letter.lower()) for letter in letters]
print(new_list)
When I upload the code to the browser I get a 'Nonetype' object is not an iterable. Makes sense... considering Powershell tells me it is initially viewed as a Nonetype. But, why?
You are almost there. It should be:
letters = ['A', 'B', 'C', 'D']
new_list = [letter.lower() for letter in letters]
print(new_list)
E.g. have a look here for comparison of list comprehension vs for loop.
The above code snippet with a list comprehension equals to:
letters = ['A', 'B', 'C', 'D']
new_list = list()
for letter in letters:
new_list.append(letter.lower())
print(new_list)
You should be doing something like this:
letters = ['A', 'B', 'C', 'D']
new_list = [letter.lower() for letter in letters]
print(new_list)
The error comes from this line:
[new_list.append(letter.lower()) for letter in letters]
On new_list.append(...) you have not declared the new_list array variable (it doesn't exist), and you're telling it to append something to it.
List comprehensions are a replacement for creating a new list and then appending to it. You create it and populate it in one go

Append list to itself in python [duplicate]

This question already has answers here:
What do ellipsis [...] mean in a list?
(5 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 2 years ago.
When I have a list, say mylist = ['a', 'b', 'c'] and I try to append it to its self
mylist.append(mylist)
I get
['a', 'b', 'c', [...]]
Which is a recursive list, for example, mylist[3][3][1] outputs 'b'
I expected to get
['a', 'b', 'c', ['a', 'b', 'c']]
My first question is how can I get what I expected (if there are many methods I would prefer the most performant).
My second question, is what's the reason for this "unexpected" behaviour.
Thanks.
I use python3.8.2
You can use list comprehensions:
mylist.append([x for x in mylist])

Combination of list of list elements [duplicate]

This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 4 years ago.
I want a list which is a combination of list of list elements
For example:
my input
x = [['P'], ['E', 'C'], ['E', 'P', 'C']]
The output should be
['PEE','PEP','PEC','PCE','PCP','PCC']]
Any help is highly appreciated.
Use itertools
[''.join(i) for i in itertools.product(*x)]
Note: assuming that last one should be 'PCC'
here is a solution
def comb(character_list_list):
res = ['']
for character_list in character_list_list:
res = [s+c for s in res for c in character_list]
return res
On your example, it gives, as expected
>>> comb([['P'], ['E', 'C'], ['E', 'P', 'C']])
['PEE', 'PEP', 'PEC', 'PCE', 'PCP', 'PCC']
A shorter version is possible using functools.reduce(), but the use of this function is not recommanded.

how to print a list like a string? [duplicate]

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 4 years ago.
I am trying to print a list like a string:
list = ['a', 'b', 'c', 'd', 'e', 'f']
the output I want it to be;
abcdef
You should use the join() method, in python, join() returns a string in which the string elements of sequence have been joined by str separator.
str = ''
sequence = ['a', 'b', 'c', 'd', 'e', 'f']
print str.join(sequence)
You can pass any list or tuple as sequence.
If you just want to print it, you can make use of the end parameter of print. It defaults to "\n" and is what is printed at the end of the string passed to it:
for i in list:
print(i, end="")
If you actually want the string, you can just add them together(not in all python versions):
string=""
for i in list:
sting+=i
If you know how many items are in your list:
string=list[0]+list[1]+list[2]+list[3]+list[4]
or:
print(list[0],list[1],list[2],list[3],list[4], sep="")
(sep is what is printed between each string, defaults to " ", However the two above are quite messy.

Split the word by each character python 3.5 [duplicate]

This question already has answers here:
How do I split a string into a list of characters?
(15 answers)
Closed 2 years ago.
I tried using all the methods suggested by others but its not working.
methods like str.split(), lst = list("abcd") but its throwing error saying [TypeError: 'list' object is not callable]
I want to convert string to list for each character in the word
input str= "abc" should give list = ['a','b','c']
I want to get the characters of the str in form of list
output - ['a','b','c','d','e','f'] but its giving ['abcdef']
str = "abcdef"
l = str.split()
print l
First, don't use list as a variable name. It will prevent you from doing what you want, because it will shadow the list class name.
You can do this by simply constructing a list from the string:
l = list('abcedf')
sets l to the list ['a', 'b', 'c', 'e', 'd', 'f']
First of all, don't use list as name of the variable in your program. It is a defined keyword in python and it is not a good practice.
If you had,
str = 'a b c d e f g'
then,
list = str.split()
print list
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Since split by default will work on spaces, it Will give what you need.
In your case, you can just use,
print list(s)
>>>['a', 'b', 'c', 'd', 'e', 'f', 'g']
Q. "I want to convert string to list for each character in the word"
A. You can use a simple list comprehension.
Input:
new_str = "abcdef"
[character for character in new_str]
Output:
['a', 'b', 'c', 'd', 'e', 'f']
Just use a for loop.
input:::
str="abc"
li=[]
for i in str:
li.append(i)
print(li)
#use list function instead of for loop
print(list(str))
output:::
["a","b","c"]
["a","b","c"]

Categories