Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

other possible way to duplicate a string from one variable in python

I am trying to make a function to duplicate a string from one variable and returned it with two arguments, what im trying to do is if I type pie then it will return ('pie','pie'), here is what i already do :

def duplicateVariabel(kata):
  kata_dua = kata
  return kata,kata_dua
print(duplicateVariabel("aku"))

so basically I'm trying to find another way to duplicate aku without using kata_dua = kata but still return 2 variables

like image 516
Walls Avatar asked Nov 29 '25 16:11

Walls


2 Answers

>>> kata = "kata"
>>> (kata, kata)
('kata', 'kata')

No need to create a new variable.

like image 82
Michael Bianconi Avatar answered Dec 02 '25 04:12

Michael Bianconi


Try this:

def duplicateVariabel(kata):
   return kata,kata
print(duplicateVariabel("aku"))

duplicateVariabel returns the tuple containing the string values.

so basically im trying to find another way to duplicate aku without using kata_dua = kata but still return 2 variables

Note: Strings in Python are immutabe and variables holds references (they are similar to pointers) to the values/object. So, you aren't basically duplicating the strings. See this.

See this for the difference between shallow and deep copy.

kata_dua = kata

The above statement doesn't do shallow or deep copy. It only copies the reference stored in variable kata to kata_dua variable. After the above statement, they both point to the same object (for example, "aku")

If you don't believe me, try this:

abcd = "abhi"
efgh = abcd
print("ABCD is ", id(abcd))
print("EFGH is ", id(efgh))

They both print the same value.

like image 28
abhiarora Avatar answered Dec 02 '25 05:12

abhiarora