How can I multiply elements in nested lists in Python and print the new list?

  • Context: Python 
  • Thread starter Thread starter Kolika28
  • Start date Start date
  • Tags Tags
    List Python
Click For Summary

Discussion Overview

The discussion revolves around how to multiply elements in nested lists in Python, specifically focusing on modifying the last element of inner lists by a given number. Participants explore various coding approaches, potential pitfalls, and the implications of list copying in Python.

Discussion Character

  • Technical explanation
  • Conceptual clarification
  • Debate/contested
  • Homework-related
  • Mathematical reasoning

Main Points Raised

  • One participant asks how to multiply the last element of inner lists by a number x.
  • Some participants suggest using a for loop to iterate through the list and modify the inner lists.
  • Another participant points out that the inner loop may be unnecessary since the inner lists only contain two elements.
  • There is a discussion about the correct way to copy lists in Python, with some noting that using list() only copies references to the original sublists.
  • Several participants propose using list comprehensions as a way to create a new list without modifying the original.
  • One participant mentions using the copy.deepcopy() function to avoid modifying the original list.

Areas of Agreement / Disagreement

Participants express varying opinions on the best approach to copy lists and modify elements. There is no consensus on a single method, as multiple strategies are discussed and some participants clarify misunderstandings about list copying.

Contextual Notes

Participants highlight that copying a list in Python does not copy the elements themselves, but rather the references to those elements, which can lead to unintended modifications of the original list.

Who May Find This Useful

This discussion may be useful for individuals learning Python, particularly those interested in list manipulation and understanding how references work in the language.

Kolika28
Messages
146
Reaction score
28
I have a list containing several lists with two elements each. I want to multiply the last element in the inner lists with a number x, and then print the new list. How do I do this?
 
Last edited:
Technology news on Phys.org
Is this a homework assignment? If so what is the actual problem you're trying to solve.

Start by making a for loop to iterate through the list and within the for loop work with the inner list.
 
jedishrfu said:
Is this a homework assignment? If so what is the actual problem you're trying to solve.

Start by making a for loop to iterate through the list and within the for loop work with the inner list.

This is not an assignment, I'm just practicing for a test. I tried this, but I did'nt work properly, so I must be doing something wrong. My x is 5 by the way
2.PNG
 
I don't see the index, j, actually used in the inner loop. That seems wrong. I think mylist should have 3 indices in the inner loop.

CORRECTION: Looking at the definition of mylist, the inner loop is not needed and there are only two indices.
 
Last edited:
  • Like
Likes   Reactions: Kolika28
Because your inner list has only two elements and you know you want the change a specific one then there's no need for the inner for loop.

The trailing print statement should be outdented to run once outside the for loop or you should print only mylist[ i ].

The inner list looks to be an ordered set of related data and could be better represented by a tuple rather than a list. Of course this would mean unpacking, processing and making a new tuple.

Lastly try not to use common words like sum for variable names especially here when you’re not even summing. Sum may be a python keyword or function too which could cause issues at some point.
 
  • Like
Likes   Reactions: Kolika28 and FactChecker
Python:
for pair in mylist:
    pair[1] *= 5
 
  • Like
Likes   Reactions: Kolika28, FactChecker and jedishrfu
General code:
Code:
mylist=[[2000, 28],
        [2001, 32],
        [2002, 36],
        [2003, 39]]

newlist=list(mylist)
number=len(newlist)
for i in range(number):
    newlist[i][-1]=round(newlist[i][-1]*5)
print(newlist)
print(mylist)

So I have almost figured it out now. I only have one problem left: when I'm working with newlist, the orginal also gets modified. My textbook tells me that I have to use the function list() to make a copy of the orginal, but it doesn't work.
 
Python:
mylist=[m[:-1]+[5*m[-1]] for m in mylist]
m becomes each element (i.e., each sub-list) in mylist in turn. m[:-1] is every element in m except the last, and m[-1] is the last element. Technically this structure is called a generator, because it's a process for generating modified elements from mylist. Wrapping the whole thing in square brackets gets python to execute the generator and return the result as a list.
 
Kolika28 said:
General code:
Code:
mylist=[[2000, 28],
        [2001, 32],
        [2002, 36],
        [2003, 39]]

newlist=list(mylist)
number=len(newlist)
for i in range(number):
    newlist[i][-1]=round(newlist[i][-1]*5)
print(newlist)
print(mylist)

So I have almost figured it out now. I only have one problem left: when I'm working with newlist, the orginal also gets modified. My textbook tells me that I have to use the function list() to make a copy of the orginal, but it doesn't work.
I think the problem is that list(mylist) makes a copy of your list, but it still contains the same sublists - you didn't copy those. So you need to copy newlist[i] before modifying it.
 
  • Like
Likes   Reactions: Kolika28
  • #10
Ibix said:
I think the problem is that list(mylist) makes a copy of your list, but it still contains the same sublists - you didn't copy those. So you need to copy newlist[i] before modifying it.
Hmm, I'm not quite sure if I understand what you mean...
 
  • #11
mylist consists of pointers to the sublists. Copying mylist to newlist just copies the pointers, but those pointers still point to the original sublists. So changing the sublist entries through the newlist copy actually changes the original sublists.
 
  • Like
Likes   Reactions: Ibix
  • #12
Kolika28 said:
Hmm, I'm not quite sure if I understand what you mean...
What @FactChecker says.

Lists in python don't, strictly speaking, contain their elements. Instead, they contain the memory addresses where their elements can be found. So copying the list doesn't copy the sub-lists, just the addresses, and modifying the sub-list "in" the copy modifies the sub-list "in" the original.

So you need to make your newlist from copies of each of the sublists in the original.

Edit: think of a list of the things in a drawer. Copying the list doesn't copy the contents of the drawer.
 
  • Like
Likes   Reactions: Kolika28 and FactChecker
  • #13
You can use a list comprehension if you want to create a new list without modifying the original one.
Python:
newlist = [[x, 5*y] for [x, y] in mylist]
 
  • #14
Ibix said:
What @FactChecker says.

Lists in python don't, strictly speaking, contain their elements. Instead, they contain the memory addresses where their elements can be found. So copying the list doesn't copy the sub-lists, just the addresses, and modifying the sub-list "in" the copy modifies the sub-list "in" the original.

So you need to make your newlist from copies of each of the sublists in the original.

Edit: think of a list of the things in a drawer. Copying the list doesn't copy the contents of the drawer.
Ohh, I see. Thank you for a good explanation!
wle said:
You can use a list comprehension if you want to create a new list without modifying the original one.
Python:
newlist = [[x, 5*y] for [x, y] in mylist]

Thank you, I will try this!
 
  • #15
Kolika28 said:
Ibix said:
What @FactChecker says.

Lists in python don't, strictly speaking, contain their elements. Instead, they contain the memory addresses where their elements can be found. So copying the list doesn't copy the sub-lists, just the addresses, and modifying the sub-list "in" the copy modifies the sub-list "in" the original.

So you need to make your newlist from copies of each of the sublists in the original.

Edit: think of a list of the things in a drawer. Copying the list doesn't copy the contents of the drawer.
Ohh, I see. Thank you for a good explanation!

In case you don't know it already it's maybe worth adding that not only the contents of lists but variables in general are all references (a.k.a. pointers) in Python. This has a visible effect in code like the following:
Python:
>>> a = [1, 2, 3, 4, 5]
>>> b = a
>>> b[2] = 99
>>> a
[1, 2, 99, 4, 5]
This behaviour is also why the code I posted above with the pair variable correctly modifies your original list.
 
  • Like
Likes   Reactions: Kolika28
  • #16
wle said:
In case you don't know it already it's maybe worth adding that not only the contents of lists but variables in general are all references (a.k.a. pointers) in Python. This has a visible effect in code like the following:
Python:
>>> a = [1, 2, 3, 4, 5]
>>> b = a
>>> b[2] = 99
>>> a
[1, 2, 99, 4, 5]
This behaviour is also why the code I posted above with the pair variable correctly modifies your original list.

Thanks, I really appreciate your help. I tried using the function copy.deepcopy(), and it worked out great!
 
  • Like
Likes   Reactions: FactChecker

Similar threads

  • · Replies 2 ·
Replies
2
Views
1K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 43 ·
2
Replies
43
Views
5K
  • · Replies 29 ·
Replies
29
Views
4K
Replies
6
Views
3K
  • · Replies 4 ·
Replies
4
Views
4K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 7 ·
Replies
7
Views
5K
  • · Replies 9 ·
Replies
9
Views
1K