0

I'm learning Python, using CPython. I'm reading how to use lists and tuples properly, so I've designed a really simple program to see if I know what I'm doing, but as I can see, there is something wrong in theory and I don't know what is

I've designed 2 functions: foo and foo2, intendend to print the same result, but it's not.

# Wrong output
def foo(v):
    print(v[:][0])

# Right output
def foo2(v):
    for i in range(0, 2):
        print(v[i][0])

v = [('ABC', 'DEF', 1), ('ABC2', 'DEF2', 2)]
foo(v)
foo2(v)

RESULT: Output from foo: ('ABC', 'DEF', 1) Output from foo2: ABC ABC2

EXPECTED: Output from foo: ABC ABC2 Output from foo2: ABC ABC2

What is hapenning here?

Felipe
  • 55
  • 6
  • 1
    standard list doesn't works like numpy array. `[:][0]` doesn't get first elements from all data in list. In numpy array you could use `v[:,0]` to get list `['ABC' 'ABC2']` - but you still have to use `" ".join()` or `for`-loop to correctly display it. – furas Aug 10 '19 at 21:45
  • In the Python shell, what do you get when you enter `v[:]`? Of possible interest: [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – wwii Aug 10 '19 at 21:55

3 Answers3

1

In foo, you pass in a list of tuples, and operate on it with v[:]. All this is doing is basically making a copy of the list you passed in. Demonstrably:

>>> v
[('ABC', 'DEF', 1), ('ABC2', 'DEF2', 2)]
>>> v[:]
[('ABC', 'DEF', 1), ('ABC2', 'DEF2', 2)]

So, when you access the first element of v[:], all you get back is the tuple ('ABC', 'DEF', 1).

JSON Brody
  • 736
  • 1
  • 4
  • 23
0

v[:] does nothing other than duplicate the list, it's a list slice that goes from start to end of the list

if you want to make this short you could use zip(*v), zip((1,2), (3,4)) combines 1 with 3 and 2 with 4. the * star operator is used to get elements from a list as separate function arguments

laundmo
  • 318
  • 5
  • 16
0

Well, the [:] does not do anything, so you are just printing the first entry of the list,

which is the tuple ('ABC', 'DEF', 1)

In foo2, you are first picking a tuple ([ i ]), and then the first entry of the tuple ([0]).

OnPoint
  • 141
  • 1
  • 6