What would be the inverse of the list() function [duplicate] - python

This question already has answers here:
How to concatenate (join) items in a list to a single string
(11 answers)
Closed 3 years ago.
Say that you had this:
Laugh = 'hehe'
The practicality of this of example doesn't really matter but if you wanted to put laugh into a list by doing: laugh = list(laugh) and you do laugh[1] = 'a'. How would you put laugh into 'hahe'?

In general, to convert a list into a string, use ''.join:
laugh = 'hehe'
laugh = list(laugh)
laugh[1] = 'a'
laugh = ''.join(laugh)
This is better than other methods such as using a for-loop:
new_laugh = ''
for c in laugh:
new_laugh += c

The simplest way (using just the + operator - in case you want to have a user defined function to do get the task done) would be to add the components of the list into one string:
def string_to_list(L):
S = ""
for i in L:
S = S + str(L)
return S
string_to_list(laugh)
You can also use the join() function, to do the same:
Laugh = ''.join(laugh)

Related

How do I change a singular element of a python list to a string [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 10 months ago.
Say I have a python list with 5 elements; list = ['a','b','c','d','e']. And I want to change it into 5 different strings so that each element is its own string, for example,
str1 = a str2 = b str3 = c str4 = d str5 = e
How would that be done?
Note: I would want it to be done autonomously if possible as the number of elements in a list is variable according to the data that is input at the beginning of the original code.
list_ = ['a','b','c','d','e']
You can use something called list unpacking, that you can do this way:
a, b, c, d, e = list_
As #Mark told you in the comments...
I'd be curious to know when str1, str2, etc. is preferable to s[1] , s[2]. It sounds like you are about to make a mistake you will later regret.
...you should avoid this approach.
If you don't know the lenght, you should read this, which suggests you to use the * star operator...
first, second, *others, third, fourth = names
...until you have the whole list unpacked.
Since you don't want to write an hell of if/elif/else over the lenght, I would suggest you to use exec to create variables on fly, even if (like Mark said) it's a bad idea.
I really want you to get that this is a bad idea, but you can use unpacking for useful scopes, in this case I would suggest you to read this, this and the respective PEP.

Adding a suffix to both elements in a list and to a variable at the same time [duplicate]

This question already has answers here:
Python star operator in assignments
(2 answers)
Closed 2 years ago.
Say I have a list of strings:
myList = ['apple','banana','orange']
and another string saved into a single variable:
myVariable = 'fudge'
I want to add the suffix _df2 to every element in myList, and also to myVariable. Therefore, I want my result to look like this:
>> myList
['apple_df2', 'banana_df2', 'orange_df2']
>> myVariable
'fudge_df2'
Currently I am achieving this with the following code:
myList = [fruit + '_df2' for fruit in myList]
myVariable = myVariable + '_df2'
I am wondering, however, since I am adding the same suffix both times, is there a way to sum these two steps up into one?
Create a single list headed by your singleton item, universally apply the modification, then unpack in the same order.
myVariable, *myList = [x + '_df2' for x in [myVariable, *myList]]
I would probably still prefer the two-line solution, though. You aren't just appending the same value to each element; you also need to preserve the list structure of the original list.
You could do the following, but as #YevhenKuzmovych says, its not a good solution.
myList, myVariable = [fruit + '_df2' for fruit in myList], myVariable + '_df2'

convert list into string? [duplicate]

This question already has answers here:
How to convert list to string [duplicate]
(3 answers)
Closed 2 years ago.
Here is my list ['k:1','d:2','k:3','z:0'] now I want to remove apostrophes from list item and store it in the string form like 'k:1 , d:2, k:3, z:0' Here is my code
nlist = ['k:1','d:2','k:3','z:0']
newlist = []
for x in nlist:
kk = x.strip("'")
newlist.append(kk)
This code still give me the same thing
Just do this : print(', '.join(['k:1','d:2','k:3','z:0']))
if you want to see them without the apostrophes, try to print one of them alone.
try this:
print(nlist[0])
output: k:1
you can see that apostrophes because it's inside a list, when you call the value alone the text comes clean.
I would recommend studying more about strings, it's very fundamental to know how they work.
The parenthesis comes from the way of representing a list, to know wether an element is a string or not, quotes are used
print(['aStr', False, 5]) # ['aStr', False, 5]
To pass from ['k:1','d:2','k:3','z:0'] to k:1 , d:2, k:3, z:0 you need to join the elements.
values = ['k:1','d:2','k:3','z:0']
value = ", ".join(values)
print(value) # k:1, d:2, k:3, z:0
What you have is a list of strings and you want to join them into a single string.
This can be done with ", ".join(['k:1','d:2','k:3','z:0']).

python 3.7 single line for comprehension [duplicate]

This question already has answers here:
How to reuse an expression in a comprehension expression?
(2 answers)
Closed 2 years ago.
I have a code that looks like this:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
in my original code "len" is much complicated function, is there a way to do the calcualtion of len only once?
in a traditional for loop it can be done like this:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
can you please advise how to achieve the same result without using a traditional for loop.
Thanks
You can use := operator (in case of Python 3.8+):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
Note: don't overwrite default built-in functions, in this case len(). Other functions may depend on it.

nestedLists[2][4] = "a" sets the 5th member of EVERY list in the list to "a" [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 9 years ago.
I've been learning Python 3 over the past few weeks. I've run into a snag:
Logically, the line nestedLists[2][4] = "a" should set the 5th member of the 3rd list in this list of lists to "a." Unfortunately, for reasons I don't understand, it sets the 5th member of every list in the list to "a." This is my code:
gameList = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
def buildList(gameListt):
gameListt[0] = ("~ " * 60).split()
for i in range(len(gameListt)):
gameListt[i] = gameListt[0]
return gameListt
gameList = buildList(gameList)
print(gameList)
gameList[2][4] = "a"
print(gameList)
I'm utterly lost here. The syntax checks out fine, and when I try this:
gameList = [["c","a","t"],["h","a","t"]]
gameList[0][2] = "b"
print(gameList)
It works fine, and outputs "cab" and "hat." I need help!
Thanks in advance!
gameList starts off being a list of distinct lists, however here:
for i in range(len(gameListt)):
gameListt[i] = gameListt[0]
You are making each element of gameListt the same list
You should do something like this instead
def buildList(gameListt):
for i in gameListt:
i[:] = ["~"] * 60
return gameListt
Also if you initialise gameList like this:
gameList = [[] for x in range(15)]
It's easier to see it's got 15 sublists

Categories