1

I have a list of lists and I want to print the first 2 elements of the first 2 sub-lists.

I don't know if I am approaching it in the wrong way but I don't get the desired output.

Here is my code:

x = [[1, 2, 3, 4, 5, 6],
    ['a', 'b', 'c'],
    [1.1, 2.2, 3.3]]

print(x[0:2])
print(x[0:2][0:2])

output:

[[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']]
[[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']]

expected output:

[[1, 2, 3, 4, 5, 6], ['a', 'b', 'c']]
[[1, 2], ['a', 'b']]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44

5 Answers5

3

Something like that could do the trick:

print([l[:2] for l in x[:2]])
[[1, 2], ['a', 'b']]

Explanation:

  • x[:2] (or x[0:2]) gets the first 2 sublists.
  • for l in x[:2] at each iteration assigns to l each of the sublists
  • l[:2] takes the first 2 elements of the sublist.

Why x[0:2][0:2] doesn't work?

  • x is a list of sublists.
  • x[0:2] returns a list with the first 2 sublists.
  • x[0:2][0:2] is the same to (x[0:2])[0:2] that's equivalent to x[0:2], because it takes the first 2 sublists from the first 2 sublists.
J. Ferrarons
  • 560
  • 2
  • 7
2
x = [[1, 2, 3, 4, 5, 6],
    ['a', 'b', 'c'],
    [1.1, 2.2, 3.3]]

k=[]
for y in x[0:2]:
    k.append(y[0:2])

print(k)
#[[1, 2], ['a', 'b']]
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
1

x is a list.

Clearly you expect x[:2] to be a list as well containing two elements from x, regardless of their contents.

Now write out

y = x[:2]
print(y[:2])

Clearly, that will print the first two elements of x, regardless of the contents.

The way to access the element of a list instead of a sublist is with a single integer index or by iteration.

for y in x[:2]:
    print(y[:2])

You can iterate more compactly using a comprehension:

print(*(y[:2] for y in x[:2]), sep='\n')
Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Here you can simply have your expected result with:

for item in x[:2]:
    print(item[0:2])

But if ever you had a homogeneous nested list (same number of rows and columns), you could convert it into a NumPy array and then use multidimensional slicing which is way easier. For example for a list like:

x = [[1, 2, 3],
    ['a', 'b', 'c'],
    [1.1, 2.2, 3.3]]

You can do:

x = np.array(x)
print(x[:2, :2])
Totoro
  • 474
  • 2
  • 6
  • 18
-3

I think you should try like x[1:2]i am attaching the link of similar issue solved in stack over flow that might help you Stack over flow slicing

also how python slicing works link python slicing works with description

Sweety SK
  • 351
  • 1
  • 10