0

I am a beginner in python and am trying to tackle this problem and just cannot get my output right. I am trying to change the value of an item in a list and pass the item to a new list.

mylist = []
test = ['path', 'name', 'user1', 'orig']
for i in test:
     if 'user' in i:
          mylist = 'user' # or i[:-1]
     else:
          mylist = i
mylist

any help would be appreciated or point me to the answer

Damon

Dani Mesejo
  • 55,057
  • 6
  • 42
  • 65
Damonv2
  • 3
  • 3

5 Answers5

1

You can do a list-comprehension:

test = ['path', 'name', 'user1', 'orig']

mylist = ['user' if 'user' in x else x for x in test]
# ['path', 'name', 'user', 'orig']
Austin
  • 25,142
  • 4
  • 21
  • 46
  • this is a really good example/explaniation of [list comprehensions](https://www.pythonforbeginners.com/basics/list-comprehensions-in-python) – chitown88 Dec 19 '18 at 15:49
1

Note that when you do:

`mylist = 'user'`

You are replacing whatever there was in that list with 'user'. So instead you want to specify an index, say mylist[i] = 'user', or use append.

This however can be simplified using a list comprehension:

[i if 'user' not in i else 'user' for i in l ]
['path', 'name', 'user', 'orig']
yatu
  • 80,714
  • 11
  • 64
  • 111
0

Looks like this is what you want: append

>>> mylist = []
>>> test = ['path', 'name', 'user1', 'orig']
>>> for i in test:
...      if 'user' in i:
...           mylist.append(i[:-1])
...      else:
...           mylist.append(i)
...
>>> mylist
['path', 'name', 'user', 'orig']
bison
  • 745
  • 4
  • 20
0

list comprehension probably the best answer. but since you're learnng, it's good to see the expanded way too.

mylist = []
test = ['path', 'name', 'user1', 'orig']
for x in test:
    if 'user' in x:
        x = 'user'  
        mylist.append(x)
    else:
        mylist.append(x)
mylist
chitown88
  • 24,774
  • 3
  • 26
  • 56
0

Since you're learning, I propose a solution as similar as possible to your approach:

mylist = []
test = ['path', 'name', 'user1', 'orig']
for i in test:
     if 'user' in i:
          mylist.append('user') # or i[:-1]
     else:
          mylist.append(i)

print(mylist)

As you can see, I added the method .append(), list method that allows you to insert an element at the end of a list.

What you were doing, with the = sign, was an assignment: the value of mylist was reassigned each time.

In this QA you can find an explanation on how to use .append(), or you can have a look at the official documentation

Gsk
  • 2,802
  • 5
  • 24
  • 28